0.7 is not less than 0.7 but wrong result gets printed [duplicate]

流过昼夜 提交于 2019-12-12 03:31:09

问题


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");
}

回答1:


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

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...

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?"

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");
}


来源:https://stackoverflow.com/questions/25458046/0-7-is-not-less-than-0-7-but-wrong-result-gets-printed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!