嵌套while循环遇到麻烦

时间:2016-02-23 23:48:25

标签: c while-loop nested-loops

目标是根据统一号码将平均值分配给不同的玩家。问题是它不断跳过第二个printf,并且switch语句中的字符不起作用。我确信这对我来说是一个非常简单的错误,但我似乎无法找到它。

int main(){
float ab;
float hits;
int un;
char pa;
printf("Please enter the player number, or -1 to exit. \n");
scanf("%d%*c \n", &un);
while( un!= -1)
{
    printf("Please enter either an H for a hit or an O for a out, enter E to stop. \n");
    scanf("%c%*c", &pa);
    while(pa != 'E')
    {
            switch (pa) 
            {
            case 'h':
            case 'H': 
                ab += 1;
                hits +=1;
                break;

            case 'o':
            case 'O': 
                ab+=1;
                break;

            default:
                printf("Error: Please insert an O or H \n");
                break;
            }
        float average = (ab/hits);
        printf("Player %d's score is equal to: %d \n", un, average);

        printf("Please enter the player number, or -1 to exit. \n");

        scanf("%d%*c \n", &un);
    }

}
return 0;
}

1 个答案:

答案 0 :(得分:0)

您的循环嵌套不正确,您的scanf来电会挂起,您需要预先初始化abhits,而您的最终printf有格式不正确。

这里有更正的代码[请原谅无偿的风格清理]:

#include <stdio.h>

int
main()
{
    float ab;
    float hits;
    int un;
    char pa;

    while (1) {
        printf("Please enter the player number, or -1 to exit.\n");
#if 0
        scanf("%d%*c \n", &un);
#else
        scanf(" %d", &un);
#endif
        if (un == -1)
            break;

        ab = 0;
        hits = 0;

        printf("Please enter either an H for a hit or an O for a out, enter E to stop.\n");
        while (1) {
#if 0
            scanf("%c%*c", &pa);
#else
            scanf(" %c", &pa);
#endif
            if ((pa == 'E') || (pa == 'e'))
                break;

            switch (pa) {
            case 'h':
            case 'H':
                ab += 1;
                hits += 1;
                break;

            case 'o':
            case 'O':
                ab += 1;
                break;

            default:
                printf("Error: Please insert an O or H\n");
                break;
            }
        }

        float average = (ab / hits);

#if 0
        printf("Player %d's score is equal to: %d\n", un, average);
#else
        printf("Player %d's score is equal to: %g\n", un, average);
#endif
    }

    return 0;
}