浮点数仅打印整数部分

use*_*000 1 c++ floating-point

我有一个这样的程序:

#include <iostream>
using namespace std;

int main ()
{
    double x;
    for (int i = 1; i < 100; i++)
    {
        cout << (x = i/100) << endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在运行它时,我只得到:

0
0
0
[...]
Run Code Online (Sandbox Code Playgroud)

我在Cygwin-g ++和MinGW-g ++上测试了这个; 版本4.7.2.哪里可能是问题?

Som*_*ude 7

这是因为既i100为整数时,编译器整数除法.

解决此问题的最简单方法是使用double文字100.0:

cout << (x = i/100.0) << endl;
Run Code Online (Sandbox Code Playgroud)

  • @BoBTFish [浮点文字默认为双倍.](http://en.cppreference.com/w/cpp/language/floating_literal) (2认同)