gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:12:55 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com