我的输出流中出现奇怪的数字,这些数字出现在输出文本中(在控制台中)。无论我输入什么数字,数字似乎都以相同的顺序出现。它们分别是 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/