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

C++编程出现点问题 求解答!!

YZAM 发布于 2010-04-05 13:03, 517 次点击
建立类cylinder,包括两个数据成员radius和height,分别表示圆柱体的半径和高,cylinder类的构造函数被传递了两个double值来初始化这两个成员,定义成员函数area()和volume用来求圆柱体的表面积和体积,定义成员函数print()打印cylinder类的相关信息。最后函数中cylinder类的设计进行测试

我的编程如下 但无法让s,v在print()里输出 为什么 求解 !1谢谢
#include<iostream>
using namespace std;
const pi=3;
class cylinder{
   private:
       double s,radius;
       double v,height;
   public:
       cylinder(double r,double h)
       {radius=r;height=h;}
      void area()
       {double s;
       s=2*pi*radius*height;
       cout<<"s="<<s<<endl;
      }
      void volume()
       {double v;
       v=pi*radius*radius*height;
       cout<<"v="<<v<<endl;
     }
      void print()
       {cout<<"radius="<<radius<<endl;  // 为什么不能用print输出 s,v ?
       cout<<"height="<<height<<endl;}
};
    void main()
       {cylinder A(2.00,3.00);
    A.area();
    A.volume();
      A.print();
      
       }
2 回复
#2
书呆2010-04-05 13:17
程序代码:
class cylinder
{
private:
    double radius;
    double height;
public:
    cylinder(double r,double h)
    {
        radius=r;
        height=h;
    }
   
    double area()
    {
        return (2*pi*radius*height);
    }
    double volume()
    {
        return (pi*radius*radius*height);
    }
    void print()
    {
        cout<<"radius="<<radius<<endl;
        cout<<"height="<<height<<endl;
        cout<<"s="<<area()<<endl;
        cout<<"v="<<volume()<<endl;
    }
};
#3
yyblackyy2010-04-05 13:58
#include<iostream>
using namespace std;
const int pi=3;
class cylinder{
   private:
       double s,radius;
       double v,height;
   public:
       cylinder(double r,double h)
       {radius=r;height=h;}
      void area()
       {//double s; 省略,否则赋值的是局部变量s的值,不是类成员的s,那么你的print 就输出无意义的s值,这就是你说的输不出吧
       s=2*pi*radius*height+2*pi*radius*radius;//这才是表面积 ,你的是侧面积
       cout<<"s="<<s<<endl;
      }
      void volume()
       {//double v;  // 同上
       v=pi*radius*radius*height;
       cout<<"v="<<v<<endl;
     }
      void print()
       {
          cout<<"radius="<<radius<<endl;  // 为什么不能用print输出 s,v ?
       cout<<"height="<<height<<endl;
       cout<<"s="<<s<<endl;           //输出s
       cout<<"v="<<v<<endl;           //输出 v
      }
};
    void main()
       {cylinder A(2.00,3.00);
    A.area();
    A.volume();
      A.print();
      
       }
1