C ++ Cout浮点问题

时间:2009-09-10 21:27:44

标签: c++ floating-point

#include <iostream>
using namespace std;
int main()
{
        float s;
        s = 10 / 3;
        cout << s << endl;
        cout.precision(4);
        cout << s << endl;
        return 0;

}

为什么输出不显示3.333而只显示3 ??

3 个答案:

答案 0 :(得分:6)

因为您正在使用s = 10 / 3

进行整数除法

尝试

s = 10.0f / 3.0f

答案 1 :(得分:3)

进行常量浮点除法的正确方法是:

s = 10.f / 3.f; // one of the operands must be a float

如果没有f后缀,您正在执行double除法,并发出警告(从floatdouble)。

您还可以投射其中一个操作数:

s = static_cast<float>(10) / 3; // use static_cast, not C-style casts

导致正确的分裂。

答案 2 :(得分:2)

10/3是整数除法。您需要使用10.0 / 3或(浮点)10/3或10 / 3.0等

相关问题