Mengubah mode pembulatan float

Aug 26 2020

Memiliki kode seperti di bawah ini:

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

Saya berharap untuk menerima sth. seperti itu:

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

tapi mendapat:

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

Mengapa mengubah mode pembulatan tidak berhasil?

PS.

Saya menjalankan kode pada VS2020 di Win 10 64-bit

Jawaban

1 BarrnetChou Aug 27 2020 at 02:26

Saya menyarankan agar Anda dapat mengalikan angka, membulatkannya, dan membaginya.

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