在输入“y”或“n”之前,如何继续循环程序

问题描述 投票:2回答:2

我希望程序不断要求用户输入另一个字母,直到输入“y”或“n”。 while循环无法正常运行。到目前为止这是我的代码:

#include<stdlib.h>

int main(void)
{
    char answer;

    printf("Please enter a letter: ");
    scanf("%c", &answer);

    while (answer!= 'y' || answer!= 'n')
    {
        printf("Please enter another letter:");

        scanf("%c", &answer);

    }

    printf("You entered either yes or no\n");

        system("pause");
        return 0;
}
c
2个回答
1
投票

这是一个固定版本。请注意包括stdio.h以及将||固定到&&以及"%c"之前的空间为" %c"

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
    char answer;
    printf("Please enter a letter: ");
    scanf("%c", &answer);
    while (answer != 'y' && answer != 'n')
    {
        printf("Please enter another letter:");
        scanf(" %c", &answer);
    }
    printf("You entered either yes or no\n");
    system("pause");
    return 0;
}

1
投票
 while (answer!= 'y' || answer!= 'n')

应该

 while (answer!= 'y' && answer!= 'n')

因为你answer变量中的每个角色的第一个条件总是如此。

© www.soinside.com 2019 - 2024. All rights reserved.