Comparison of a float with a value in C

本文深入探讨了C语言中浮点数比较时类型转换的原理,通过具体实例展示了浮点数如何从单精度转换为双精度,并解释了这种转换对比较操作结果的影响。详细分析了不同浮点数在表达上的差异及其对程序输出的直接影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Predict the output of following C program.

#include<stdio.h>
int main()
{
     float x = 0.1;
     if (x == 0.1)
         printf ( "IF" );
     else if (x == 0.1f)
         printf ( "ELSE IF" );
     else
         printf ( "ELSE" );
}

The output of above program is “ELSE IF” which means the expression “x == 0.1″ returns false and expression “x == 0.1f” returns true.

Let consider the of following program to understand the reason behind the above output.

#include<stdio.h>
int main()
{
    float x = 0.1;
    printf ( "%d %d %d" , sizeof (x), sizeof (0.1), sizeof (0.1f));
    return 0;
}

The output of above program is “4 8 4” on a typical C compiler. It actually prints size of float, size of double and size of float.

The values used in an expression are considered as double (double precision floating point format) unless a ‘f’ is specified at the end. So the expression “x==0.1″ has a double on right side and float which are stored in a single precision floating point format on left side. In such situations float is promoted to double (seethis). The double precision format uses uses more bits for precision than single precision format.
Note that the promotion of float to double can only cause mismatch when a value (like 0.1) uses more precision bits than the bits of single precision. For example, the following C program prints “IF”.

#include<stdio.h>
int main()
{
     float x = 0.5;
     if (x == 0.5)
         printf ( "IF" );
     else if (x == 0.5f)
         printf ( "ELSE IF" );
     else
         printf ( "ELSE" );
}

Output:

IF

You can refer Floating Point Representation – Basics for representation of floating point numbers.

This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值