简体   繁体   中英

Rounding floating point program

I'm trying to write a C program to find the smallest positive integer x so that (1/x) * x is not equal to 1, using single precision. And I do it again with double precision. I know that the x for single precision is 41, however when I test it by writing C code, I still get 1.00000

This is my test code

int main()
{
    float x = 41;
    float div = 1/x;
    float test = div * x;

    printf("%f\n", test);
}

I get 1.0000 instead of a 0.999999

You are not seeing the problem using

printf("%f\n", test);

since the default precision used by printf for floating point numbers is 6 . If you increase the precision to 10 , you will see that the number is not 1.0 .

printf("%.10f\n", test);

prints 0.9999999404 for me.

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