#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?C++ Cout浮点数问题
#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?C++ Cout浮点数问题
,因为你正在做s = 10/3
整数除法尝试
s = 10.0f/3.0f
做一个恒定的浮动师正确的方法是:
s = 10.f/3.f; // one of the operands must be a float
没有f
后缀,你是做double
师,发出警告(从float
到double
)。
您也可以施放一个操作数:
s = static_cast<float>(10)/3; // use static_cast, not C-style casts
在正确分割了。
关闭,但现在是双倍的。 – GManNickG 2009-09-10 21:29:20
现在怎么样? – jcopenha 2009-09-10 21:33:07
右键。 :P [15chars] – GManNickG 2009-09-10 21:33:30