简体   繁体   English

为什么在C中将较大的double转换为long有时返回正数,而其他时候返回负数?

[英]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: 我将其放入iOS测试用例并在(32位iPad)模拟器中运行了它:

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). 我知道为什么它将long的大double值截断为long(32位)的最大值。 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). 强制转换变量将导致运行时代码执行转换,并且所产生的溢出产生最大负数(0x80000000是未定义的结果,但是此运行时正在执行的操作)。 Casting the constant will cause the compiler to convert the number and it does convert to the maximum positive number (0x7FFFFFFF). 强制转换常量将导致编译器转换该数字,并且确实转换为最大正数(0x7FFFFFFF)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM