簡體   English   中英

if / else語句在while循環內被忽略

[英]If/else statement is ignored inside while loop

運行此命令時,在情況1中顯示“輸入颶風#1的最大速度: ”的行,然后輸入“ 34”,它將返回“風速(以結為單位:25.6789)”“輸入最大風速#2颶風: “但我正在嘗試使其返回“颶風無效的風速。請重試。”

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
 int x;
 int year;
 int tropical_storms;
 int hurricanes;
 int a=1;
 int windspeed;
 float knots;
 float conversion=0.868976;
  printf("                 HEg v1.0 \n");
  printf("0. Exit\n");
  printf("1. Submit Hurricane Season Storm Information\n");
  printf("2. Submit Storm Data\n");
  printf("3. Print Hurricane Season Analysis\n");
  printf("4. Print Storm Analysis\n");
  printf("\n");
  printf("Please Enter Selection: ");
  scanf("%d", &x);
  switch(x) { 
     case 0:
          printf("Thank you for using HEg v1.0");
          break;
     case 1:
          printf("Enter the year: ");
          scanf("%d", &year);
          printf("Enter the number of tropical storms in 2009: ");
          scanf("%d", &tropical_storms);
          printf("Enter the number of Hurricanes in 2009: ");
          scanf("%d", &hurricanes);
          while(a<=hurricanes){ 
               printf("Enter the max windspeed of hurricane #%d: ", a);
               scanf("%d", &windspeed);
               a++;
               if(windspeed>74){
               knots=windspeed*conversion;
               printf("Wind speed in knots: %.4f \n", knots); 
               }
               else{
                 printf("Invalid Windspeed for Hurricane. Try again");
               }
          }

          break;
     case 2:
          printf("Menu option not available in HEg v1.0");
          break;
     case 3:
          printf("Menu option not available in HEg v1.0");
          break;
     case 4: 
          printf("Menu option not available in HEg v1.0");
          break;
     default:
          printf("no");    
          break;
  } 
  system("PAUSE>nul");  
  return 0;
}

理想情況下,它應該可以工作,但是我仍然可以對scanf的讀數表示懷疑。 每當您讀取變量並按Enter時,scanf都會將enter保留在緩沖區中,並將其作為下一個while語句的輸入。 if語句導致失敗,並運行else語句。 將輸入作為整數是惡魔。 將輸入作為字符串並使用atoi函數轉換為整數。

您是否在if-else中看到任何一個printf語句?
實際上,可能您甚至沒有進入while循環。
a1 ,那么您將使用什么作為颶風的測試值?

忠告:您需要更具描述性地命名變量,而不僅僅是axy等。 它確實有助於調試和注釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM