【问题标题】:My C++ output is always 0 [duplicate]我的 C++ 输出始终为 0 [重复]
【发布时间】:2018-01-14 00:31:03
【问题描述】:

我目前正在尝试将公式输入到代码中,但是当我执行时,它总是出现为零。我试着环顾四周,但更多的论坛帖子有特定的错误,导致它们输出为零,并且与我正在尝试做的事情无关。所以如果有人能成为第二双眼睛,那就太棒了。

【问题讨论】:

  • 请将代码发布为代码而非图像,获取tour 并阅读help page。首先阅读these C++ books 之一。
  • 请记住,C++ 不是数学。 a = b; 并不意味着 a始终b 具有相同的值。
  • 您在第 5 行调用未定义的行为
  • 为什么这个问题的副本是愚人节帖子?
  • @ArnavBorborah:因为上面OP的源代码是图像,而不是文本。

标签: c++


【解决方案1】:

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

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

由于 c 不是双精度数,您也会损失精度。

【讨论】:

  • 更准确地说,在计算 c 时,ab未初始化,并且可以包含任何随机内容。
  • @Galik 我知道我只是用空这个词来避免混淆他
  • 感谢您,我是新手,正在尝试学习 c++,您只需回答我的问题是什么!谢谢!!!
【解决方案2】:

不幸的是,您正在对两个未定义的空数字进行(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;”)。

很抱歉误用了代码选择。我觉得没有它看起来会不对。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 2016-09-22
    • 2014-06-04
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多