2016-11-10 53 views
1

因此,在我的程序中沒有語法錯誤,這是一個邏輯錯誤。我的問題是,當我嘗試運行它時,只有我的printf語句會執行,但在此之後它會關閉我的程序,不會讓我的while loop詢問任何數據,直到用戶放入-1來停止我的while循環。我的程序在關閉前不會運行我的while循環

#include <stdio.h> 
// prototypes 
void updateLevel(int PlayerPoints, int playerLevels[]); 
void displayLevels(int ArrayName[]); 

//main begins 
int 
main (void){ 
    //arrays and varibles 
    int playerLevels[6] = {0}; 
    int playerPoints = 0; 

    printf("Player points (-1 to quit) "); 
    scanf("%d" , &playerPoints); 
    //while loop to process input data 
    while(playerPoints =! -1){ 
     scanf("Player points (-1 to quit) %d" , &playerPoints); 
     updateLevel(playerPoints, playerLevels); 
    } 

    displayLevels(playerLevels); 
    return(0); 
} 
//main ends 

//functions 
void updateLevel(int playerPoints, int playerLevels[]){ 
    if(playerPoints >=50) 
    playerLevels[6]++; 
    else if (playerPoints >=40) 
     playerLevels[5]++; 
    else if (playerPoints >= 30) 
     playerLevels[4]++; 
    else if (playerPoints >= 20) 
     playerLevels[3]++; 
    else if (playerPoints >= 10) 
     playerLevels[2]++; 
    else 
     playerLevels[1]++; 

} 

void displayLevels(int playerLevels[]){ 
    printf("T O T A L S\n"); 
    printf("Level 1 %d\n", playerLevels[1]); 
    printf("Level 2 %d\n", playerLevels[2]); 
    printf("Level 3 %d\n", playerLevels[3]); 
    printf("Level 4 %d\n", playerLevels[4]); 
    printf("Level 5 %d\n", playerLevels[5]); 
    printf("Level 6 %d\n", playerLevels[6]); 
} 

回答

1

對於初學者,而不是這個

while(playerPoints =! -1){ 
        ^^ 

必須有

while(playerPoints != -1){ 
        ^^ 

原來的語句相當於

while(playerPoints = 0){ 

因此不執行循環。

然而該方案不確定的行爲,因爲你定義的6個元素

int playerLevels[6] = {0}; 

的數組,但您要訪問的存儲器陣列超越

if(playerPoints >=50) 
playerLevels[6]++; 

指數爲陣列的有效範圍是[0, 5]指數從0開始。

+0

omg我甚至沒有注意到操作員,但非常感謝你!它的工作原理非常感謝你! –

+0

@GabrielFregoso沒問題。這是一個錯字。:) –