【发布时间】:2021-11-05 21:23:50
【问题描述】:
#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;
}
实际上,虽然没有编译错误,但这段代码给了我垃圾值。它没有给我想要的面积和周长输出。那么为什么我会得到垃圾值呢?
【问题讨论】:
-
请edit您的问题正确缩进您的代码。代码,因为它目前的格式,很难跟上。
-
当您将输入数据存储在成员变量中时,为什么还要将参数传递给
Area和peri?您传递的变量也未初始化。Area函数也不返回值。如果你把它们调得足够高,你应该会得到一个编译警告。 -
你不需要
int x,y,z;;你永远不会初始化它们。你不需要int peri(int a,int b,int c),你的三角形有它自己的a,b.c。替换为int peri()。Area也一样。为什么peri返回值而Area打印值却什么也不返回?为什么Area大写而peri不是?为什么s和area是类成员,即使您在单个函数中初始化并使用它们? -
` s = (a + b + c) / 2;` 将因整数除法而截断。哎呀。使用
0.5f * (a + b + c)。 -
@n.1.8e9-where's-my-sharem。是的,我遇到了问题......所以当我将成员变量作为输入时,我不必将参数传递给成员函数?对吗?