Home > Enterprise >  Unable to determine and print out truncation error from int to float implicit cast
Unable to determine and print out truncation error from int to float implicit cast

Time:05-01

Learning C with a book. In my book, a similar code should have yielded "3.000000" as truncation error. The book is a bit older, still on C99 standard. What am I missing?

#include <stdio.h>

int main()
{
    int i;
    float f;

    scanf("%d", &i); // 123456789
    f = i; // implicit type cast

    printf("int: %d with size %d\n", i, sizeof(i)); // int: 123456789 with size 4
    printf("float: %f with size %d\n", f, sizeof(f)); // float: 123456792.000000 with size 4

    printf("error: %f with size %d\n", f-i, sizeof(f-i)); // error 0.000000 with size 4

    return 0;
}

CodePudding user response:

I think 0.000000 is correct. C99 6.3.1.8p1 says:

Otherwise, if the corresponding real type of either operand is float, the other operand is converted, without change of type domain, to a type whose corresponding real type is float.

So in f-i, the i is converted to float, yielding the same value as f. I am not sure how your book's compiler could have got 3.000000.

If you really want to see the truncation error, do (double)f - i.

  • Related