【问题标题】:Why isn't my while loop functioning properly?为什么我的 while 循环不能正常运行?
【发布时间】:2022-01-06 21:37:51
【问题描述】:

我的任务是仅当用户键入“n”或“N”时才退出循环。

这是我的代码:

#include<stdio.h>
int main()
{
    char alpha;

    printf("This loop will repeat. Do you wnat to repeat? (Press n or N to exit). ");
    scanf("%c", &alpha);
    
    if(alpha != 'n' || alpha != 'N')
    {
        printf("Do you still want to repeat? (Press n or N to exit). ");
    }
    
    while(alpha != 'n' || alpha != 'N');
    return 0;
}

问题是我的代码根本没有循环。

【问题讨论】:

  • 考虑一下。 alpha 总是不等于“n”或不等于“N”。你需要&amp;&amp;,而不是||。你应该有while,你有if,你应该删除第二个while

标签: c loops while-loop


【解决方案1】:

代码中的注释:

#include <stdio.h>

int main(void)
{
    char alpha;

    printf("This loop will repeat. Do you wnat to repeat? (Press n or N to exit). ");
    // You need a "do" to start a block of code,
    // otherwise the "while" loop runs forever
    do
    {
        // Put a space before the format specifier to consume the trailing
        // newline left by previous calls to scanf
        scanf(" %c", &alpha);
        // You want the "and" operator, not "or"
        if(alpha != 'n' && alpha != 'N')
        {
            printf("Do you still want to repeat? (Press n or N to exit). ");
        }
    }
    // Same here, you want the "and" operator, not "or"
    while(alpha != 'n' && alpha != 'N');
    return 0;
}

更好的方法(只测试一次条件并检查scanf的结果):

#include <stdio.h>

int main(void)
{
    char alpha;

    printf("This loop will repeat. Do you wnat to repeat? (Press n or N to exit). ");
    while (scanf(" %c", &alpha) == 1)
    {
        if(alpha != 'n' && alpha != 'N')
        {
            printf("Do you still want to repeat? (Press n or N to exit). ");
        }
        else break;
    }
    return 0;
}

【讨论】:

猜你喜欢
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多