2016-11-10 50 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没问题。这是一个错字。:) –