简体   繁体   中英

Could anyone tell me why float can't hold 3153600000?

I know this is stupid but I'm a quiet a noob in a programming world here is my code.

This one works perfectly:

#include <stdio.h>

int main() {

    float x = 3153600000 ;

    printf("%f", x);

    return 0;
}

But this one has a problem:

#include <stdio.h>

int main() {

    float x = 60 * 60 * 24 * 365 * 100 ;

    printf("%f", x);

    return 0;
} 

So 60 * 60 * 24 * 365 * 100 is 3153600000 right??? if yes then why does it produced different results??? I got the overflow in the second one it printed "-1141367296.000000" as a result. Could anyone tell me why?

You're multiplying integers, then putting the result in a float. By that time, it has already overflowed.

Try float x = 60.0f * 60.0f * 24.0f * 365.0f * 100.0f; . You should get the result you want.

60 is an integer, as are 24 , 365 , and 100 . Therefore, the entire expression 60 * 60 * 24 * 365 * 100 is carried out using integer arithmetic (the compiler evaluates the expression before it sees what type of variable you're assigning it into).

In a typical 32-bit architecture, a signed integer can only hold values up to 2,147,483,647. So the value would get truncated to 32 bits before it gets assigned into your float variable.

If you tell the compiler to use floating-point arithmetic, eg by tacking f onto the first value to make it float, then you'll get the expected result. (A float times an int is a float, so the float propagates to the entire expression.) Eg:

float x = 60f * 60 * 24 * 365 * 100;

Doesn't your compiler spit this warning? Mine does:

warning: integer overflow in expression

The overflow occurs before the all-integer expression is converted to a float before being stored in x. Add a.0f to all numbers in the expression to make them floats.

If you multiply two integers, the result will be an integer too.

60 * 60 * 24 * 365 * 100 is an integer.

Since integers can go up to 2^31-1 ( 2147483647 ) such values overflows and becomes -1141367296 , which is only then converted to float.

Try multiplying float numbers, instead of integral ones.

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