c - c中常数的默认数据类型是什么?

标签 c types

float x=2, y=2.6;

if(x==2); 
if(x==2.0) //both these conditions evaluate to be true

但是,

 if(y==2.6); 

评估为假

谁能解释一下常量的默认数据类型是什么,为什么我会得到这样的结果

最佳答案

float x=2, y=2.6;
//           ^^^ double, internally converted to float during the initialization
//      ^ int, internally converted to float during the initialization

if (x == 2) // compare double converted from float (x) with double converted from int (2)
if (x == 2.0) // compare double converted from float (x) with double (2.0)

if (y == 2.6) // compare double converted from float (y) with double (2.6)

注意最后一个条件:最初 2.6 (a double) 被转换为 float;将该 float 转换回 double 并不能保证相同的值。

(double)(float)2.6 != 2.6

大概是这样的:

                 2.6 is 0b10.1001100110011001100110011001100110011001100110011001
          (float)2.6 is 0b10.10011001100110011001100
  (double)(float)2.6 is 0b10.1001100110011001100110000000000000000000000000000000
          difference is                             ^ approx. ~0.000000095367

关于c - c中常数的默认数据类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59333286/

相关文章:

c - 帮助我理解 C 中这个简单的 malloc

c - 无法识别 EOF

c - 当端口从 0 变为 1 时,如何添加 90 分钟的延迟?

java - 字节值的平均值

表示路径的 C#(非静态)类

c - 如果全局变量的值在函数中更新,它们的值是否会发生变化?

c - C语言代码如何在linux中设置路径环境变量

c# - C# 可以存储比 double 更精确的数据吗?

types - Coq 案例分析和重写函数返回子集类型

c++ - 命名空间中声明的数据类型的范围