Thay đổi chế độ làm tròn nổi
Aug 26 2020
Có mã như dưới đây:
#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);
}
Tôi mong nhận được sth. như thế:
float division : 10.000 / 3.000 = 3.334
float division : 10.000 / 3.000 = 3.333
nhưng có:
float division : 10.000 / 3.000 = 3.333
float division : 10.000 / 3.000 = 3.333
Tại sao thay đổi chế độ làm tròn không hoạt động?
Tái bút.
Tôi đang chạy mã trên VS2020 trên Win 10 64-bit
Trả lời
1 BarrnetChou Aug 27 2020 at 02:26
Tôi đề nghị bạn có thể Nhân một số, làm tròn số và chia nó.
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;
}