#include<stdio.h>
#include<iostream>
using namespace std;
class Calculate //class form
{
int r,h ;
public:
void getdata() //input data
{
cout<<"Enter the radius and height";
cin>>r>>h;
}
void Surfacearea()
{
float a;
a= ( ( 2 * 3.14 * r * r ) + ( 2 * 3.14 * r * h ) );
cout<<"the sa of cylinder is"<<a;
}
void volume()
{
float v;
v = ( 3.14 * r * r * h );
cout<<"the volume of cylinder is"<<v;
}
};
Calculate a1,a2,g;
int main()
{
g.getdata();
a1.Surfacearea();
a2.volume();
}
我得到surfacearea和音量为零,我无法在代码中找到错误,请帮助我.......................... .................................................. ..............................................
答案 0 :(得分:1)
你的课程计算没问题。
问题出在函数main中,当你调用g.getdata()时,你正在读变量'h'和amp;对象'g'的'r',然后你调用a1.SurfaceArea()和a2.volume()试图显示结果,但你从未调用过对象a1和a2 !!的函数getdata。因此'r'和'h'未被初始化为a1和a2。
所以只需在调用函数SurfaceArea和volume之前添加它,它应该可以工作:
a1.getdata();
a2.getdata();
答案 1 :(得分:-1)
您可能想要考虑您的课程设计。以下是我的写作方式:
#include <iostream>
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
using namespace std;
class Cylinder
{
public:
Cylinder() :
m_radius(0.0),
m_height(0.0)
{
}
void SetHeight(double height)
{
m_height = height;
}
void SetRadius(double radius)
{
m_radius = radius;
}
double GetSurfaceArea() const
{
double area = (2.0 * M_PI * m_radius * m_radius) + (2.0 * M_PI * m_radius * m_height);
return area;
}
double GetVolume() const
{
double volume = (M_PI * m_radius * m_radius * m_height);
return volume;
}
private:
double m_radius;
double m_height;
};
int main()
{
double radius = 0.0;
double height = 0.0;
cout << "Enter the radius and height";
cin >> radius >> height;
Cylinder cylinder;
cylinder.SetHeight(height);
cylinder.SetRadius(radius);
cout << "the sa of cylinder is: " << cylinder.GetSurfaceArea() << endl;
cout << "the volume of cylinder is: " << cylinder.GetVolume() << endl;
return 0;
}