为什么这个程序会继续显示结果?

时间:2012-11-27 17:27:36

标签: c

我写过这个程序,它将输入的高度(以厘米为单位)更改为英尺和英寸。当我运行它时,结果不断停止。有谁知道为什么?

#include <stdio.h>

int main (void)
{
  float heightcm;
  float feet;
  float inch;

  printf("Enter height in centimeters to convert \n");
  scanf("%f", &heightcm);

  while (heightcm > 0)
  {
   feet = heightcm*0.033;
   inch = heightcm*0.394;

   printf("\n %0.1f cm = %0.2f feet and %0.2f inches \n", heightcm,feet,inch);
  }
 return 0;
}

1 个答案:

答案 0 :(得分:3)

你做了一个无限循环:

  while (heightcm > 0)   // if user enters a height > 0 we get in
  {
   feet = heightcm*0.033; // update feet 
   inch = heightcm*0.394; // update inches

   // print the result
   printf("\n %0.1f cm = %0.2f feet and %0.2f inches \n", heightcm,feet,inch); 
  }

没有循环中的heightcm更改,这意味着它始终是> 0,并且您的函数将永远循环并且永不终止。 if检查在这里更有意义:

  if (heightcm > 0)   // if user enters a height > 0 we get in
  {
   feet = heightcm*0.033; // update feet 
   ...

或者您可以使用while循环并继续要求更多输入:

  while (heightcm > 0)
  {
    printf("Enter height in centimeters to convert \n");
    scanf("%f", &heightcm);
    ...

这可能是你想要的(循环直到用户输入非正数)