Noo*_*der 1 c++ class object area
#include <iostream>
#include <math.h>
#include <conio.h>
using namespace std;
class Triangle
{
public:
int a, b, c;
void getdata();
int peri(int a, int b, int c)
{
return a + b + c;
}
float s;
float area;
float Area(int a, int b, int c)
{
s = (a + b + c) / 2;
area = sqrt(s * (s - a) * (s - b) * (s - c));
cout << area;
}
};
void Triangle::getdata()
{
cin >> a >> b >> c;
}
int main()
{
int x, y, z;
cout << "Enter the three sides";
Triangle t1;
t1.getdata();
cout << "The area of that triangle is " << t1.Area(x, y, z) << "and the perimeter "
<< t1.peri(x, y, z);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
实际上,尽管没有编译错误,但这段代码给了我垃圾值。它没有给我所需的面积和周长输出。那么为什么我会得到垃圾值呢?
这里从三角形初始化a、b、c :
\nvoid Triangle::getdata( )\n{\n cin>>a>>b>>c;\n}\nRun Code Online (Sandbox Code Playgroud)\n但是这里你使用了没有初始化的x,y,z ,就有问题了
\nint main()\n{\n int x,y,z; //<-- these three variables are nowhere initialised\n cout<<"Enter the three sides";\n Triangle t1;\n t1.getdata();\n cout<<"The area of that triangle is "\n <<t1.Area( x, y, z) //where x, y, z are initialised??\n <<"and the perimeter " \n <<t1.peri(x,y,z); //where x, y, z are initialised?\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n更新 1:正如 @Bathsheba 所指出的, s = (a + b + c) / 2;将由于整数除法而截断。哎呀。使用 0.5f * (a + b + c)。\xe2\x80\x93
这就是你应该如何实现你的三角形
\nclass Triangle\n{\npublic:\n int a, b, c;\n void getdata();\n int peri() //remove the arguments, the class has its own members to use\n {\n return a + b + c;\n }\n float s;\n float area;\n float Area() //remove the arguments, the class has its own members to use\n {\n s = 0.5f * (a + b + c); //As pointed by @Bathsheba\n area = sqrt(s * (s - a) * (s - b) * (s - c));\n cout << area;\n }\n\n};\nRun Code Online (Sandbox Code Playgroud)\n然后这样写main函数
\nint main()\n{\n //no additional x, y, z\n cout<<"Enter the three sides";\n Triangle t1;\n t1.getdata();\n cout<<"The area of that triangle is "\n <<t1.Area() //no arguments\n <<"and the perimeter " \n <<t1.peri(); //no arguments\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n