因此,作为作业的一部分,我正在工作如果表达式: (double) (float) x == (double) x 是否返回 awlays 1。(x 是有符号整数)
它适用于除 INT_MAX 之外的所有值。我想知道为什么会这样?如果我打印这些值,它们都会显示相同的值,即使对于 INT_MAX 也是如此。
x = INT_MAX ;
printf("Signed X: %d\n",x);
float fx1 = (float)x;
double dx1 = (double)x;
double dfx = (double)(float)x;
printf("(double) x: %g\n",dx1);
printf("(float) x: %f \n",fx1);
printf("(double)(float)x: %g\n",dfx);
if((double) (float) x == (double) x){
printf("RESULT:%d\n", ((double)(float) x == (double) x));
}
编辑:整个程序:
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int main(int argc, char *argv[]){
//create random values
int x = INT_MAX ;
printf("Signed X: %d\n",x);
float fx1 = (float)x;
double dx1 = (double)x;
double dfx = (double)(float)x;
printf("(double) x: %g\n",dx1);
printf("(float) x: %f \n",fx1);
printf("(double)(float)x: %g\n",dfx);
if((double) (float) x == (double) x){
printf("RESULT:%d\n", ((double)(float) x == (double) x));
}
return 0;
}//主函数结束
最佳答案
int
和 float
的表示形式很可能具有相同的位数,即 32。float
有一个尾数、一个指数和符号位,因此尾数必须小于 31 位,这是较大的 int
值(例如 INT_MAX
)所需的。因此,存储在 float
中时会损失精度。
关于类型转换有符号为 double 与类型转换为 float 然后 double 结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26262187/