2017-10-13 65 views
0

我在输出流中出现输出文本(在控制台中)的奇怪数字。无论我输入什么数字,这些数字似乎都以相同的顺序出现。它们分别是0,80,0。我的代码下面是一个示例输出。出现在输出流中的未输入的C++数字

#include <iostream> 
#include <iomanip> 
#include <cmath> 
using namespace std; 
int main() 
{ 
    int a, b, c; 

    //write program so that a<=b<c or find a way to sort the program so the numbers are in ascending order 

    cout << "This program uses the input of the lengths of 3 sides of a triangle to determine if the triangle is a right triangle." << endl; 
    cout << "Enter the length of side 'a'. " << a << "\n"; 
    cin >> a; 
    cout << "Enter the length of side 'b'. " << b << "\n"; 
    cin >> b; 
    cout << "Enter the length of side 'c'. " << c << "\n"; 
    cin >> c; 
    if ((a * a) + (b * b) == (c * c)) // This means (a^2)+(b^2)=(c^2) 
    { 
     cout << "This is a right triangle." << "\n"; 
    } 
    else if ((b * b) + (c * c) == (a * a)) 
    { 
     cout << "This is a right triangle." << "\n"; 
    } 
    else if ((a * a) + (c * c) == (b * b)) 
    { 
     cout << "This is a right triangle." << "\n"; 
    } 
    else 
    { 
     cout << "This is not a right triangle." << "\n"; 
    } 
    return 0; 
} 

该程序使用输入三角形的三边长度来确定三角形是否是直角三角形。 输入边a的长度。 0 输入边“b”的长度。 80 输入边“c”的长度。 0 这不是一个直角三角形。

+0

好的,我在输出中删除了不必要的“abc's”,但现在我的控制台正在输出:这个程序使用三角形3边长度的输入来确定三角形是否是直角三角形。 输入边a的长度。 输入边“b”的长度。 输入边“b”的长度。 输入边“c”的长度。 输入边c的长度。 这不是一个直角三角形。 这不是一个直角三角形。 –

+0

这些数字是您的变量的未初始化值,您使用提示输出,这是每个提示行的'<< a <<'部分。不要这样做。 – davidbak

+0

不知道为什么它会做这些双重句子 –

回答

1

cout << "Enter the length of side 'a'. " << a << "\n"; 

<< a指示程序打印的a当前值。此时a没有定义的值,但该变量存在,所以试图打印它在语法上是正确的并编译。在undefined behaviour使用该uninitializeda结果,所以任何可能发生,但什么是最有可能发生的是什么垃圾碰巧在现在a占用的内存被打印出来。在你的情况下,结果是0.

解决方法是不打印出a的值。似乎没有必要这样做。

cout << "Enter the length of side 'a'.\n"; 

重复此侧b和c。

+0

谢谢。这看起来有伎俩。 –

+0

如果解决了你的问题,你应该接受这个正确的答案。 – Buddy

0

在读取它们之前,您正在打印未初始化的变量a,bc