gpt4 book ai didi

c - 我的程序在关闭前不会运行我的 while 循环

转载 作者:太空宇宙 更新时间:2023-11-04 03:26:48 24 4
gpt4 key购买 nike

所以我的程序中没有语法错误,这是一个逻辑错误。我的问题是,当我尝试运行它时,只有我的 printf 语句会执行,但之后它关闭了我的程序,不允许我的 while 循环 请求更多数据,直到用户输入-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]);
}

最佳答案

对于初学者而不是这个

while(playerPoints =! -1){
^^

必须有

while(playerPoints != -1){
^^

原语句等同于

while(playerPoints = 0){

所以循环没有执行。

但是程序有未定义的行为,因为你定义了一个包含 6 个元素的数组

int playerLevels[6] = {0};

但是你正试图访问数组之外​​的内存

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

数组索引的有效范围是[0, 5]索引从0开始。

关于c - 我的程序在关闭前不会运行我的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40519777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com