c++ - 尽管我提供了参数,为什么我在这里得到垃圾值?
问题描述
#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;
}
实际上,虽然没有编译错误,但这段代码给了我垃圾值。它没有给我想要的面积和周长输出。那么为什么我会得到垃圾价值呢?
解决方案
在这里,您从三角形初始化a、b、c :
void Triangle::getdata( )
{
cin>>a>>b>>c;
}
但是这里你使用了没有初始化的x,y,z,有问题
int main()
{
int x,y,z; //<-- these three variables are nowhere initialised
cout<<"Enter the three sides";
Triangle t1;
t1.getdata();
cout<<"The area of that triangle is "
<<t1.Area( x, y, z) //where x, y, z are initialised??
<<"and the perimeter "
<<t1.peri(x,y,z); //where x, y, z are initialised?
return 0;
}
更新 1:正如@Bathsheba 所指出的, s = (a + b + c) / 2;
由于整数除法,将截断。哎呀。使用 0.5f * (a + b + c)。——</p>
这就是你应该如何实现你的三角形
class Triangle
{
public:
int a, b, c;
void getdata();
int peri() //remove the arguments, the class has its own members to use
{
return a + b + c;
}
float s;
float area;
float Area() //remove the arguments, the class has its own members to use
{
s = 0.5f * (a + b + c); //As pointed by @Bathsheba
area = sqrt(s * (s - a) * (s - b) * (s - c));
cout << area;
}
};
然后像这样写main函数
int main()
{
//no additional x, y, z
cout<<"Enter the three sides";
Triangle t1;
t1.getdata();
cout<<"The area of that triangle is "
<<t1.Area() //no arguments
<<"and the perimeter "
<<t1.peri(); //no arguments
return 0;
}
推荐阅读
- python - 替换 Python 列表中元素的值
- oracle - 将 Oracle 自治数据库连接到 .net 实体框架
- angular - 为什么在对接 Angular 项目时显示“找不到 Angular 项目”
- python-3.x - 如何编写for循环以使其在第N次出现条件时停止?
- c++ - 从基类实例调用派生类方法而不进行强制转换
- python - 如何在 pandas 和 python 的 grouby 数据图中显示线条的标签
- html - 浏览器因嵌入网站而停止工作,但仅在显示图标时
- ffmpeg - Raspberry Pi Zero W 上的 FFmpeg 安装:对 __atomic 的未定义引用
- sql - 在 Postgres 中搜索部分存在于字符串中的多个单词
- linux - 如何检查我的交通控制规则的运行情况?