因此我的程序中没有语法错误,这是一个逻辑错误。我的问题是,当我尝试运行它时,我的printf
语句才会执行但在此之后关闭我的程序,不让我的while loop
再询问数据,直到用户输入-1
来停止我的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]);
}
答案 0 :(得分:1)
对于初学者而不是这个
while(playerPoints =! -1){
^^
必须有
while(playerPoints != -1){
^^
原始陈述相当于
while(playerPoints = 0){
所以不执行循环。
然而,程序具有未定义的行为,因为您定义了一个包含6个元素的数组
int playerLevels[6] = {0};
但您正在尝试访问数组之外的内存
if(playerPoints >=50)
playerLevels[6]++;
数组的有效索引范围是[0, 5]
索引从0开始。