首页 > 解决方案 > 尽管我提供了参数,为什么我在这里得到垃圾值?

问题描述

#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;
}

实际上,虽然没有编译错误,但这段代码给了我垃圾值。它没有给我想要的面积和周长输出。那么为什么我会得到垃圾价值呢?

标签: c++classobjectarea

解决方案


在这里,您从三角形初始化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;
}

推荐阅读