我不能提供一个while循环相等的条件? [英] Can I not provide an equality condition in a while loop?

查看:77
本文介绍了我不能提供一个while循环相等的条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写这篇code,只有'你好'得到了印。

 浮动X = 1.1;
的printf(你好\\ n);
而(X-1.1 == 0)
{
   的printf(%F \\ N,X);
   X = X-1;
}


解决方案

当你正在处理浮点运算,你没有得到的结果如你所愿。

你所看到的是:


  1. 1.1 重新presented为浮动 X

  2. ,而语句, 1.1 的类型为双击,而不是浮动。因此, X 提升为双击的减法和比较才制成。

    您失去这些步骤precision。因此, X-1.1 不计算为 0.0


您可以看到预期的结果,如果您使用适当的浮点常量。

 的#include<&stdio.h中GT;TEST1无效()
{
   的printf(在测试1 ... \\ n);
   浮动X = 1.1;   //使用文字float类型,而不是增加一倍。
   如果(X-1.1F == 0)
   {
      的printf(真\\ n);
   }
   其他
   {
      的printf(假\\ n);
   }
}空TEST2()
{
   的printf(在测试1 ... \\ n);   //使用double类型的变量,而不是浮动。
   双X = 1.1;
   如果(X-1.1 == 0)
   {
      的printf(真\\ n);
   }
   其他
   {
      的printf(假\\ n);
   }
}诠释的main()
{
   TEST1();
   TEST2();
   返回0;
}

输出:

 在测试1 ...
真正
在测试2 ...
真正

I wrote this code and only 'Hello' got printed.

float x=1.1;
printf("Hello\n");
while(x-1.1==0)
{
   printf("%f\n",x);
   x=x-1;
}

解决方案

When you are dealing with floating point operations, you don't get the results as you would expect.

What you are seeing is:

  1. 1.1 is represented as a float in x.
  2. In the while statement, 1.1 is of type double, not float. Hence, x is promoted to a double before the subtraction and comparison is made.

    You lose precision in these steps. Hence x-1.1 does not evaluate to 0.0.

You can see expected results if you use appropriate floating point constants.

#include <stdio.h>

void test1()
{
   printf("In test1...\n");
   float x=1.1;

   // Use a literal of type float, not double.
   if (x-1.1f == 0)
   {
      printf("true\n");
   }
   else
   {
      printf("false\n");
   }
}

void test2()
{
   printf("In test1...\n");

   // Use a variable of type double, not float.
   double x=1.1;
   if (x-1.1 == 0)
   {
      printf("true\n");
   }
   else
   {
      printf("false\n");
   }
}

int main()
{
   test1();
   test2();
   return 0;
}

Output:

In test1...
true
In test2...
true

这篇关于我不能提供一个while循环相等的条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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