C - 循环不继续

标签 c loops

为什么我在 char 答案中输入字母 y 后这个循环没有继续?

我认为 getchar() 会有所帮助,但它似乎没有做任何事情。

#include <stdio.h>

int main(void)
{
    char answer = 'y';
    int num = 0;
    printf("Enter a number: \n");
    scanf("%d", &num);

    while(answer != 'n')
    {
        int mult = 1;
        int k = 1;
        while (k <= num)
        {
            mult *= k;
            k++;
        }
        printf("%d! = %d\n", num, mult);

        printf("Would you like to try another number? \n");
        printf("Enter: y for yes | n for no\n");
        getchar();
        scanf("%c", &answer);
    }       
}

最佳答案

我对你的程序做了一些更正。

  1. 很难理解您的程序的作用。通过为 factorial 定义一个单独的可重用函数,我使您的程序更具可读性和模块化。
  2. 如果用户输入了 'y',则再次询问用户号码更有意义。所以,我已经移动了所需的代码。
  3. 我不建议在程序中混合使用scanfgetchar。所以,我们可以只对程序使用scanfscanf() 函数在尝试解析字符以外的转换之前自动删除空格。字符格式(主要是 %c;还有扫描集 %[…] — 和 %n)是异常(exception);他们不会删除空格。

使用带有前导空白的“%c”来跳过可选的空格。不要在 scanf() 格式字符串中使用尾随空白。

请注意,这仍然不会消耗输入流中留下的任何尾随空格,甚至不会消耗到行尾,所以如果在同一输入流上也使用 getchar() 或 fgets() 时要小心。我们只是让 scanf 在转换前跳过空格,就像它对 %d 和其他非字符转换所做的那样。

#include <stdio.h>


unsigned long factorial(unsigned long num)
{
    unsigned long mult = 1;
    unsigned long k = 1;
    while (k <= num) {
        mult *= k;
        k++;
    }

    return mult;
}

int main(void)
{
    char answer = 'y';

    do {
        int num = 0;
        printf("Enter a number: \n");
        scanf(" %d", &num);


        unsigned long mult = factorial(num);
        printf("%d! = %lu\n", num, mult);

        printf("Would you like to try another number? \n");
        printf("Enter: y for yes | n for no\n");
        scanf(" %c", &answer);

    } while (answer != 'n');  

    return 0;   
}   

关于C - 循环不继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53410581/

相关文章:

c - 循环长度 - 时间控制 - C

python-3.x - 如何在 Pandas DF 列中删除连续的相似数字

Python 多元简单线性回归

linux - 根据文件名模式将多个文件 move 到多个目录,同时排除某些文件

loops - JavaFX 8 : Iterate through TableView cells and get graphics

python-3.x - 打印各种组合中的第一个组合

c - 为什么 GCC 9.1.0 有时会提示这种 strncpy() 的使用?

c++ - 无法在 OpenSSL 中设置公钥/私钥

c - 从 GLib 单链表中弹出

c - libxml2 和 XPath 在 ANSI C 中遍历 child 和 sibling