0.7不小于0.7,但打印错误的结果 [英] 0.7 is not less than 0.7 but wrong result gets printed

查看:73
本文介绍了0.7不小于0.7,但打印错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里, a应打印为0.7< 0.7为假,但会打印'c'。

Here 'a' should get printed as 0.7 < 0.7 is false, but 'c' is printed.

#include<stdio.h>
void main()
{
  float a=0.7;
  if(a<0.7)
    printf("c");
  else
    printf("a");
}


推荐答案

您似乎误解了浮点数数字。请参阅此问题

You seem to misunderstand floating point numbers. See this question.

您可以做的一件事是,认为永远不会精确到0.7,所以也许我不能肯定,但是我可以得到 close ...

One thing you can do is think "Well, it will never be exactly 0.7, so maybe I can't judge for sure, but I can get close...

然后,您选择一个粒度,例如百万分之一,您可以尝试比较整数四舍五入后的结果 ie6 * a 整数四舍五入后的结果 1e6 * 0.7 看到的不是很多是 a< 0.7 ?,但 a 合理,足够接近,小于 0.7

Then, you pick a granularity, say, one millionth. You can try comparing the integer rounded result of ie6 * a to the integer rounded result of 1e6 * 0.7 to see not so much "is a < 0.7?", but "is a reasonably, close-enough, less than 0.7?"

或者,只是比较相同的类型。如评论中所述,也许 0.7 不是 float 文字,但 double 文字,请确保它是 float 可以确定为文字,并打印'a'

Or, just compare to the same type. As said in the comments, maybe 0.7 is not a float literal but a double literal. Ensure it's a float literal to be sure, and 'a' is printed.

void main()
{
  float a=0.7;
  if(a<0.7f)
    printf("c");
  else
    printf("a");
}

这篇关于0.7不小于0.7,但打印错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆