C++ Cout浮点问题

guj*_*ujo 2 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;

}
Run Code Online (Sandbox Code Playgroud)

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

小智 6

因为你正在做整数除法 s = 10 / 3

尝试

s = 10.0f / 3.0f
Run Code Online (Sandbox Code Playgroud)