0

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

#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;
}
4

1 回答 1

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

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

于 2012-11-27T18:14:34.553 回答