2017-10-13 73 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