简体   繁体   中英

Changing float rounding mode

Having the code like below:

#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);
}

I'd expect to receive sth. like that:

float division : 10.000 / 3.000 = 3.334 
float division : 10.000 / 3.000 = 3.333 

but got:

float division : 10.000 / 3.000 = 3.333 
float division : 10.000 / 3.000 = 3.333

Why doesn't changing the rounding mode works?

PS.

I'm running the code on VS2020 on Win 10 64-bit

I suggest that you could Multiply the number, round it, and divide it.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM