注册 登录
编程论坛 C++教室

帮我优化一下!

Soul寂 发布于 2008-11-20 22:19, 684 次点击
#include <iostream>
using namespace std;
int temp;
class CFT
{
private:
    double length;
    double width;
    double height;
    double S;
   
public:

    void set_value();
    void show_value();
   
};


void CFT::set_value()
{
    cout<<"please enter numbers for"<<" "<<temp<<":"<<endl;
    cout<<"length:";
    cin>>length;
    cout<<endl;
    cout<<"width:";
    cin>>width;
    cout<<endl;
    cout<<"height:";
    cin>>height;
    cout<<endl;
}
void CFT::show_value()
{
    S=length*width*height;
        cout<<"第"<<temp<<"个长方体的面积为:"<<S<<endl;
}

int main()
{
    CFT a;
    int n;
    cout<<"请输入你需要计算长方体的个数:";
    cin>>n;
    for(int i=0;i<n;i++)
    {
        temp=i+1;
        a.set_value();
        a.show_value();
      
    }
    return 0;
}


这里使用了两个函数:
void set_value();
void show_value();
分别来初始化长方体的各项数值,和计算长方体的体积。

大家可以看到,当要求的长方体不止一个的时候,使用for循环多次的调用void show_value()函数,这使用了很大的内存开销!

大家能不能帮我优化一下,不使用for循环来调用函数,而只在函数中调用n,也就将所要求的长方体的个数传给void show_value()函数

直接在void show_value()函数中多次计算,一次调用就可以求n个长方体的体积!
5 回复
#2
newyj2008-11-20 23:09
是这个意思?
程序代码:
#include <iostream>
using namespace std;

class CFT
{
private:
    static int temp;   
    double length;
    double width;
    double height;
    double S;
   
public:

    void show_value(int);
   
};
int CFT::temp=0;


void CFT::show_value(int k)
{
     for (int i=0;i!=k;++i)
     {
        cout<<"please enter numbers for"<<" "<<++temp<<":"<<endl;
        cout<<"length:";
        cin>>length;
        cout<<endl;
        cout<<"width:";
        cin>>width;
        cout<<endl;
        cout<<"height:";
        cin>>height;
        cout<<endl;   
        S=length*width*height;
        cout<<"第"<<temp<<"个长方体的面积为:"<<S<<endl;
     }   
}

int main()
{
    CFT a;
    int n;
    cout<<"请输入你需要计算长方体的个数:";
    cin>>n;
    a.show_value(n);
    system("pause");
    getchar();
    return 0;
}
#3
a198705022008-11-20 23:46
楼上这样编的话,好像感觉就没有用temp的必要了吧~~~
#4
hitcolder2008-11-21 09:29
同感,不过好像满足楼主的要求了啊
#5
Soul寂2008-11-21 18:24
感谢2楼!!!
#6
Soul寂2008-11-21 18:37
还要请教一下,为什么要设置temp为static变量:如程序所示: static int temp;   

程序中有 int CFT::temp=0;

使用这种赋值方式的变量,必须是static的吗?(我试过了如果不是static会出错!)
1