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

标签 c++ compiler-errors numbers syntax-error output

我的输出流中出现奇怪的数字,这些数字出现在输出文本中(在控制台中)。无论我输入什么数字,数字似乎都以相同的顺序出现。它们分别是 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”边的长度。 0 2个 输入边“b”的长度。 80 3个 输入“c”边的长度。 0 5个 这不是直角三角形。

最佳答案

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

<< a指示程序打印 a 的当前值.此时a没有定义的值,但变量存在,因此尝试打印它在语法上是正确的并且可以编译。使用这个 uninitialized a结果 undefined behaviour ,所以任何事情都可能发生,但最有可能发生的是现在被a占用的内存中的任何垃圾。被打印出来。在您的情况下,结果为 0。

解决方案是不要打印出 a 的值.好像没必要。

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

对 b 面和 c 面重复此操作。

关于输出流中出现尚未输入的 C++ 数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46722234/

相关文章:

c++ - 根据 Google C++ 风格指南初始化静态字符串(C 类型或 std::string)

java - 需要修复的Infix程序的后缀

c - C中n个数字按升序排列的不同组合

JavaScript 数字到单词

c++ - 错误LNK2019和LNK 1120

iphone - 如何验证 UITextField 中的输入(即数字输入)

c++ - 在不失去对其构造函数的访问的情况下稍微派生一个类

c++ - 将分钟转换为天、小时、分钟和秒

c++ - 未解析的外部静态变量

compiler-errors - 在 Solaris_x86 上构建 OpenSSL 时,Assembler 报告非法助记符