为什么这些程序以不同的顺序执行相同的计算给了我不同的输出?

问题描述:

这两个程序的输出为什么不同?我已经包含了代码,以便您可以轻松查看并尝试。任何人都可以解释给我吗?为什么这些程序以不同的顺序执行相同的计算给了我不同的输出?

#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 !

+0

该问题可能是浮点不精确。除非他没有设定变量,否则任何事情都可能发生。你能发布完整的程序吗? – leetNightshade 2014-11-14 19:22:02

+0

@spartygw [见这里](http://meta.*.com/questions/262446/are-we-being-elitist-is-there-something-wrong-with-that/262455#262455)。如果你愿意帮助他,花时间并通过编辑将问题转换成适当的形状。我的经验是,当他们的问题搁置时,最好的学习效果是由noobs采取的。 – 2014-11-14 19:29:42

+0

第一个如果我尝试1523它给我14797487059.353这是正确的一个 – 2014-11-14 19:44:57

在你的屏幕截图中的代码是不是你已经张贴在这里什么。我建议,将来如果你需要帮助解决你遇到的问题,你可以发布你遇到的问题 - 而不是完全不同的代码。

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