类型转换有符号为 double 与类型转换为 float 然后 double 结果不同

标签 c casting twos-complement

因此,作为作业的一部分,我正在工作如果表达式: (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;

}//主函数结束

最佳答案

intfloat 的表示形式很可能具有相同的位数,即 32。float 有一个尾数、一个指数和符号位,因此尾数必须小于 31 位,这是较大的 int 值(例如 INT_MAX)所需的。因此,存储在 float 中时会损失精度。

关于类型转换有符号为 double 与类型转换为 float 然后 double 结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26262187/

相关文章:

c++ - 从 int 到 float 并返回时符号发生变化

c - 为什么 ~b=-6 如果 b=5?

c - 如何循环遍历 C 中没有索引的数组?

java - C服务器和Java客户端之间的UDP连接

language-agnostic - 围绕数字 : a hypothetical two's complement question 的硬件表示

c++ - 为什么将类型 T& 转换为 T 会创建一个临时对象?

struct - golang 将字节数组转换为结构

java - 如何将 32 位 int 移位 32(再次)

c - 在 32 位 Debian Squeeze 下编译的 C 程序导致我 friend 的 64 位程序出现段错误

hadoop - PIG - HBASE - 类型转换值