2016-10-10 30 views
-4

我想運行下面的代碼,但我正在進入一個循環,我不能出去。有人可以幫我解決我的while循環嗎?它一直在運行

應該出現的錯誤消息假設用戶能夠輸入正確的範圍值。

有人可以修復這個無限循環,以便它只有當使用輸入值超出範圍時纔會出現。

#include<stdio.h> 

int main(void) { 

    int students, counter, total; 
    int marks[40]; 
    int stdno[40]; 
    total = 0; 

    printf("  ---=== IPC mark Analyser V2.0 ===---\n"); 
    printf("Please enter the number of students(between 3 and 40):"); 
    scanf("%d", &students); 

    while (students < 3 || students >40) { 
     printf("Invalid number, enter a number between 3 and 40 inclusive:"); 
     scanf("%d", &students); 
    } 

    printf("Row Std No Mrk\n"); 
    printf("--- --------- ---\n"); 

    for (counter = 0; counter < students; counter++) { 
     printf(" _________ ___\r"); 
     printf("%03d ", counter + 1); 
     scanf("%09d %3d", &stdno[counter], &marks[counter]); 

     while (marks < 0 || marks >100 || stdno < 10000000 || stdno > 999999999) { 
      printf("Error: Enter values between 0 and 100 inclusive.\n"); 
      scanf("%09d %3d", &stdno[counter], &marks[counter]); 
     } 

     return 0; 
    } 
} 
+4

請格式化您的代碼首先正確。 –

+2

您的代碼格式太差,無法閱讀此問題。 – Lundin

+0

編譯所有啓用的警告,閱讀編譯器吐出的警告並將它們視爲錯誤。 –

回答

2
  1. 首先,你必須while (marks < 0 || marks >100 || stdno < 10000000 || stdno > 999999999)的詭計循環條件是不正確的。 marksstdno是數組,不能與數字進行比較。你甚至會得到一個編譯器警告。你需要做的是與數組元素marks[counter]stdno[counter]進行比較。這是爲了讓您在循環中輸入的每個值都根據條件進行檢查。

  2. while循環應該運行兩個語句,printfscanf。在你當前的代碼中,while循環每次只執行printf。圍繞這兩個陳述你需要有大括號{

    while (marks[counter] < 0 || marks[counter] >100 || stdno[counter] < 100000000 || stdno[counter] > 999999999) 
    { 
        printf("Error: Enter values between 0 and 100 inclusive.\n"); 
        scanf("%09d %3d", &stdno[counter], &marks[counter]); 
    } 
    

可以進一步通過印刷上述相同的數目,得到的指示給用戶改善此。

while (marks[counter] < 0 || marks[counter] >100 || stdno[counter] < 100000000 || stdno[counter] > 999999999) 
{ 
    printf("Error: Enter values between 0 and 100 inclusive.\n"); 
    printf(" _________ __\r"); 
    printf("%03d ", counter + 1); 
    scanf("%09d %3d", &stdno[counter], &marks[counter]); 
} 
0

while (marks < 0 || marks >100 || stdno < 10000000 || stdno > 999999999)

此行似乎是罪魁禍首。首先,marks[]是一個數組,而不是原始類型。 marks表示數組在存儲器中的基地址。它永遠都是一樣的。你不能改變它。

C語言中,數組由identifier[]表示。它是一個同質元素的集合。每個元素必須通過使用[]括號來引用。因此,任何評估或比較必須與這些元素和數組的不是基址來完成(如果你不爲指針)

可以比較數組中的每個元素,如

while (marks[counter] < 0 || marks[counter] >100 || stdno[counter] < 10000000 || stdno[counter] > 999999999)

相關問題