【问题标题】:Why do these programs performing the same calculation in a different order give me different output?为什么这些程序以不同的顺序执行相同的计算会给我不同的输出?
【发布时间】:2014-11-14 19:16:57
【问题描述】:

为什么这两个程序的输出不同?我已包含代码,因此您可以轻松查看并尝试它。谁能给我解释一下?

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    float pi = 3.14159;
    int r;

    while (cin >> r) {
        cout << "VOLUME = " << fixed << setprecision(3)
             << pi*r*r*r*(4.0/3.0) << endl;
    }

    return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    float pi = 3.14159;
    int r;

    while (cin >> r) {
        cout << "VOLUME = " << fixed << setprecision(3)
             << (4.0/3.0)*r*r*r*pi << endl;
    }

    return 0;
}

如果我输入 1523,第一个给我 14797487059.353,这是正确答案,但第二个给我一个负数。

The 2 screens with the outputs this link include the 2 outputs the first one ir the right the second one is weird !

【问题讨论】:

  • 问题可能是浮点不精确。除非他没有设置变量,否则任何事情都可能发生。你能发布完整的程序吗?
  • @spartygw See here。如果您愿意帮助他,请花时间通过编辑来解决问题。我的经验是,当他们的问题被 [搁置] 时,菜鸟的学习效果最好。
  • 第一个如果我尝试 1523 它会给我 14797487059.353 这是正确的
  • 浮点数不够大,无法进行计算,数字溢出。如果你使用双精度,它们都输出相同的数字。
  • @ibrahiem 我已投票重新提出您的问题但仍然不够好。您应该将所有信息都放在问题中。 “输出不同”很难被称为“信息”。我已将您的评论答案编辑到文本中,下次请自己做 - 不要只在 cmets 中回答。

标签: c++


【解决方案1】:

您屏幕截图中的代码不是您在此处发布的代码。我建议将来,如果您在遇到问题时需要帮助,请发布您遇到问题的代码 - 而不是完全不同的代码。

在这种情况下,问题很简单 - r*r*r 太大而无法容纳在一个 int 中。您可以将r 更改为long long 类型,这个问题应该会消失。或者,您可以使用您在此处发布的两个代码块中的任何一个,因为它们都可以按照您的预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    相关资源
    最近更新 更多