0

入力された高さ (cm) をフィートとインチに変更するこのプログラムを作成しました。実行すると、止まることなく結果が表示され続けます。誰かが理由を知っていますか?

#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 に答える