我的C ++输出始终为0
这个问题在这里已经有了答案:
在“c”的初始化之前,您需要输入“a”和“b”的值。
当计算“c”时,“a”和“b”都是空的。
你也会失去精度,因为c不是双精度。
不幸的是,你正在对两个空的未定义数字进行计算(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;”)运行。
对于滥用代码选择感到抱歉。 没有它,我觉得它看起来不对。
链接地址: http://www.djcxy.com/p/86295.html