簡體   English   中英

While 循環在 C 程序中多次重復一系列任務

[英]While loop to repeat a series of task multiple times in C program

我正在編寫一個 C 程序來重復一系列問題的指定次數。 我要求用戶輸入他們想要的嘗試次數,然后根據他們的次數運行以下 while 循環,但問題是循環不斷重復。 它不會在指定的嘗試次數處停止。 這是代碼:

#include <stdio.h>
int main(void){

    int num1,num2,high,low,average,subtotal,total_aver;

    printf("Enter number of tries you want:");
    scanf("%d", &num1);



    while (num1 < num1 + 1) {

            printf("Try number: ");
            scanf("%d", &num2);

            printf("Enter high ");
            scanf("%d", &high);

            printf("Enter low ");
            scanf("%d", &low);

            subtotal = high + low;
            total_aver = subtotal / 2;

            printf("Average temperature is: %d", total_aver);

    }

}

如果用戶輸入 3 作為嘗試次數,那么程序應該在循環內問這些問題 3 次,但它不斷重復沒有結束。

  while (num1 < num1 + 1)   // condition is never false

嗯,這是無限循環。 它將繼續並繼續。

如果你想迭代次數,像這樣寫循環 -

  int i=0;
  while(i<num1){ 
   // your code
   i++;
 }

或者沒有任何額外的變量 -

 while(num1>0){
   // your code
    num1--;
 }

發生這種情況是因為while的條件是錯誤的。 事實上,將num1分配給任何值,當num1等於num1+1時它將退出。 這是不可能的,不是嗎? 您必須使用另一個變量來計算重復循環的次數。 以這種方式修復:

int count=0;
while(count<num+1){
    //your code
    count=count+1;
}

暫無
暫無

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

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