【问题标题】:My program wont run my while loop before it closes我的程序在关闭之前不会运行我的 while 循环
【发布时间】:2016-11-10 04:02:21
【问题描述】:

所以我的程序中没有语法错误,这是一个逻辑错误。我的问题是,当我尝试运行它时,只会执行我的 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]);
}

【问题讨论】:

    标签: c while-loop logic


    【解决方案1】:

    对于初学者而不是这个

    while(playerPoints =! -1){
                       ^^
    

    应该有

    while(playerPoints != -1){
                       ^^
    

    原语句等价于

    while(playerPoints = 0){
    

    所以循环不会被执行。

    尽管如此程序有未定义的行为,因为您定义了一个包含 6 个元素的数组

    int playerLevels[6] = {0};
    

    但您正在尝试访问数组之外​​的内存

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

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

    【讨论】:

    • 天哪,我什至没有注意到运营商,但非常感谢!它有效,所以谢谢!
    • @GabrielFregoso 没问题。这是一个错字。:)
    猜你喜欢
    • 1970-01-01
    • 2021-06-21
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    相关资源
    最近更新 更多