The following code gets wrong result when using double data type for the result y
, why is this? How do I get the correct one when using double?
You can run this code using https://godbolt.org/z/hYvxjW8xT
#include <cstdio>
#include <iostream>
int main()
{
double MYR = 153.6;
double MIYR = -153.6;
double po_size = 0.1;
printf("MYR: %.4f\n", MYR);
printf("MIYR: %.4f\n", MIYR);
printf("po_size: %.4f\n", po_size);
double y =(MYR - MIYR) / po_size; // should be 3072
printf("double res: %d\n", int(y)); // 3071 wrong
float x = (MYR - MIYR) / po_size; // should be 3072
printf("float res: %d\n", int(x)); // correct
}