为什么我的C ++程序产生无意义的数学?

时间:2016-02-18 23:40:27

标签: c++

我的计划在

之下
#include <iostream>
using namespace std;

int main()
{
    int a;
    int b; 
    int c;
    double perimeter = (a + b + c);
    int s=0.5*(a + b + c);

    cout << "Enter three numbers for the lengths of a triangle with sides a, b, and c. The first number should be the smallest, and the last should be the longest.";
    cin >> a;
    cin >> b;
    cin >> c;

    cout << "Lengths " ;
    cout << a; 
    cout << " " ;
    cout << b; 
    cout << " ";
    cout << c;

    cout << "The perimeter of the triangle is ";
    cout << perimeter ;

    cout << "s equals " ;
    cout << s;
}

这是输出:

Enter three numbers for the lengths of a triangle with sides a, b, and c.  The first number should be the smallest, and the last should be the longest.
1
2
3
Lengths 1 2 3
The perimeter of the triangle is 32061
s equals 16030 

最后我检查过,1 + 2 + 3不等于32061.发生了什么,我该如何解决?

//我猜它是因为我没有正确的标题//(#somethingoranother)?
//或者我还没有宣布它?但我不知道怎么做。 //我记得使用sqrt作为一个没有

的函数来找到过去的根
#include <iostream>
using namespace std;


    int main()
    {
    int a = 0;
    int b = 0; 
    int c = 0;
    double area = 0;
    double sqrt=0;


      cout << "Enter three numbers for the lengths of a triangle with sides a, b, and c.  The first number should be the smallest, and the last should ne the longest.";
      cin >> a;
      cin >> b;
      cin >> c;

    int perimeter = (a + b + c);
    int s=0.5*(a + b + c);

    area = sqrt ( s*(s - a)*(s - b)*(s - c) );


     cout << "The perimeter of the triangle is ";
      cout << perimeter ;
      cout << "." ;

      cout << " s equals " ;
      cout << s; 
      cout << ".  ";

      cout << "Area is ";
      cout << area;

    }

只输入&#34; area =&#34;的长公式但计算机似乎并不喜欢

3 个答案:

答案 0 :(得分:2)

尝试以下代码。在初始化三角形边的值之后,需要进行perimeters计算。

#include <iostream>
using namespace std;

int main()
{
    int a;
    int b; 
    int c;

    cout << "Enter three numbers for the lengths of a triangle with sides a, b, and c. The first number should be the smallest, and the last should be the longest.";
    cin >> a;
    cin >> b;
    cin >> c;

    cout << "Lengths " ;
    cout << a; 
    cout << " " ;
    cout << b; 
    cout << " ";
    cout << c;

    double perimeter = (a + b + c);
    int s=0.5*(a + b + c);

    cout << "The perimeter of the triangle is ";
    cout << perimeter ;

    cout << "s equals " ;
    cout << s;
}

答案 1 :(得分:1)

您正在将未初始化的值添加到一起。在对它们进行数学运算之前,您需要填写a,b和c。现在你正在这样做的方式是将随机值加在一起,这就是你得到无意义结果的原因。

答案 2 :(得分:0)

将计算移动到程序中的适当位置:在您知道输入数量之后,但在打印之前:<​​/ p>

cout << "Enter three numbers for the lengths of a triangle with sides a, b, and c.  The first number should be the smallest, and the last should be    the longest.";
cin >> a;
cin >> b;
cin >> c;

double perimeter = (a + b + c);
int s=0.5*(a + b + c);

cout << "Lengths " ;
...