输出流中出现的尚未输入的C++数字

C++ numbers appearing in output stream that have not been input

本文关键字:输入 C++ 数字 未输 输出流      更新时间:2023-10-16

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

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

该程序使用三角形 3 条边的长度的输入来确定三角形是否为直角三角形。输入边"a"的长度。02输入边"b"的长度。803输入边"c"的长度。05这不是直角三角形。

in

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

<< a指示程序打印 a 的当前值。此时a没有定义的值,但变量存在,因此尝试打印它在语法上是正确的并且可以编译。使用这种未初始化的a会导致未定义的行为,因此任何事情都可能发生,但最有可能发生的是现在被a占用的内存中碰巧被打印的任何垃圾。在您的情况下,结果为 0。

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

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

对侧 b 和 c 重复此操作。

在读取未初始化的变量之前,abc 打印它们。