简体   繁体   中英

Why does casting a large double to a long sometimes return a positive and other times return a negative value in C?

I put this into an iOS test case and ran it in the (32 bit iPad) simulator:

double whu = 3166323616091.220215;
NSLog(@"Double: %f", whu);
NSLog(@"Long:   %ld", (long)whu);
NSLog(@"Double: %f", 3166323616091.220215);
NSLog(@"Long:   %ld", (long)3166323616091.220215);

The output is:

2014-04-23 13:40:50.904 xctest[53336:303] Double: 3166323616091.220215
2014-04-23 13:40:50.905 xctest[53336:303] Long:   -2147483648
2014-04-23 13:40:50.906 xctest[53336:303] Double: 3166323616091.220215
2014-04-23 13:40:50.907 xctest[53336:303] Long:   2147483647

I get why it truncates the big double value to the max value for long (32bit). But why does casting the variable return the negative value when casting the literal returns a positive value? In fact, I don't understand why the negative is returned at all. Am I missing something having to do with precision, perhaps?

Casting a variable will result in the runtime code doing the conversion and the resulting overflow is producing the max negative number (0x80000000 an undefined result, but what this runtime is doing). Casting the constant will cause the compiler to convert the number and it does convert to the maximum positive number (0x7FFFFFFF).

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