具有如下代码:
#include <stdio.h>
#include <float.h>
#include <windows.h>
#pragma fenv_access (on)
void precission(void) {
unsigned int control_word;
int err;
float a = 10.0, b = 3.0;
char MsgBuff[300];
err = _controlfp_s(&control_word, _RC_UP, _MCW_RC);
if (err) {
sprintf_s(MsgBuff, 300, "Error n");
OutputDebugStringA(MsgBuff);
}
sprintf_s(MsgBuff, 300, "float division : %.3f / %.3f = %.3f n", a, b, a / b);
OutputDebugStringA(MsgBuff);
err = _controlfp_s(&control_word, _RC_DOWN, _MCW_RC);
if (err) {
sprintf_s(MsgBuff, 300, "Error n");
OutputDebugStringA(MsgBuff);
}
sprintf_s(MsgBuff, 300, "float division : %.3f / %.3f = %.3f n", a, b, a / b);
OutputDebugStringA(MsgBuff);
}
我希望收到这样的东西:
float division : 10.000 / 3.000 = 3.334
float division : 10.000 / 3.000 = 3.333
但得到:
float division : 10.000 / 3.000 = 3.333
float division : 10.000 / 3.000 = 3.333
为什么更改舍入模式无效?
PS。
我正在Win 10 64位上运行VS2020上的代码
我建议您可以对数字进行乘法、四舍五入和除法运算。
int main()
{
float a = 10.000;
float b = 3.000;
float c=a/b;
float d = (int)(c * 1000+1) / 1000.0;
cout << d;//d=3.334
return 0;
}