我的C ++输出始终为0

时间:2017-08-06 16:57:15

标签: c++

我目前正在尝试在代码中输入公式,但是当我执行时,它总是出现为零。我试着环顾四周,但更多的论坛帖子都有特定的错误导致他们输出零,并且与我试图做的事情没有关系。因此,如果任何人都可以成为第二双眼睛,那将是惊人的。

enter image description here

2 个答案:

答案 0 :(得分:3)

您需要在初始化“c”之前输入“a”和“b”的值。

当计算“c”时,“a”和“b”都是空的。

你也会失去精确度,因为c不是双倍的。

答案 1 :(得分:1)

不幸的是,您正在对两个空的未定义数字进行计算(a / 5) * b。 考虑一下,如果您从上到下阅读代码(通常是语言解释函数的方式),每个语句都会被解释为:

Create 'a' as an integer... (Since you didn't give it a value, I won't guarantee one for you.) in line "int a;"
Create 'b' as an integer... (You also didn't give me a value, I'll just set it to whatever was last in the location in memory.) in line "int b;"
Divide 'a' by 5 (Since you didn't explicitly provide 'a' a value, it would be hard to predict the result.) at "(a / 5)" in line "(a / 5) * b"
Multiply the last calculation by b (You didn't provide 'b' a value either, so you're creating a wildly unpredictable equation). at " * b" in line "(a / 5) * b;"
Fill in the value 'a' (Now you're actually filling in a, but you already did your calculation.) in line "cin >> a;"
Fill in the value 'b' (Same for variable b) in line "cin >> b;"

您遇到的是C ++未定义的行为。基本上,因为你没有设置' a'或者' b'一个价值,它只会留下它在内存中的最后一点,就像它的价值一样。您可以在此处详细了解:https://en.wikipedia.org/wiki/Undefined_behavior

要解决此问题,请运行两个" cin>> X"计算前的操作,但不是在声明之前(或" int a; int b;")。

对于滥用代码选择感到抱歉。如果没有它,我觉得它看起来不对。