mardi 17 septembre 2019

understand int-vs-trunc relation in double-to-int conversion

When I run following code

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    enum { FACTOR = 3 };
    double d = 1.0 / FACTOR;
    double d_i = int(d * FACTOR);
    int i_t = std::trunc(d * FACTOR);
    double d_r = std::round(d * FACTOR);
    cout << d_i << " vs " << i_t << " vs " << d_r << endl;
    return 0;
}

from within the Code::Blocks 17.12 IDE (using the all-inclusive tools as I think/hope), I get these confusing results:

0 vs 1
0 vs 1 vs 1

I tried to change the compiler, nothing changed. Finally I installed MinGW-64 version 8.1.0.

My build log shows

-------------- Clean: Debug in truncint (compiler: MinGW-w64-32bit)---------------

Cleaned "truncint - Debug"

-------------- Build: Debug in truncint (compiler: MinGW-w64-32bit)---------------

g++.exe -Wall -fexceptions -std=c++11 -g -std=c++11  -c C:\Users\[...]\truncint\main.cpp -o obj\Debug\main.o
g++.exe  -o bin\Debug\truncint.exe obj\Debug\main.o   
Output file is bin\Debug\truncint.exe with size 65.53 KB
Process terminated with status 0 (0 minute(s), 0 second(s))
0 error(s), 0 warning(s) (0 minute(s), 0 second(s))

But the strange results remain. What could be the cause of this?

Sadly this seems not to be reconstructible with online compilers.

Aucun commentaire:

Enregistrer un commentaire