为什么程序在扫描输入之前会终止?

时间:2016-03-10 16:42:09

标签: c loops for-loop

我是编程方面的新手。我正在尝试的代码是

#include <stdio.h>
int main()
{
    int n, a = 1, c = 5;
    char ch;
    do
    {
        printf("Type the last number of the series 5 * 10 * 15 * ... * N:");
        scanf("%d", &n);
        for( ; c <= n; a = a*c, c = c +5);
        {
            printf("The result is %d\nDo you want do it again? (Type 'Y' for yes and 'N' for no)", a);
            ch = getchar();
        }
    }
    while(ch=='y');
    return 0;
}

但问题是程序正在执行而不询问Y或N.循环不起作用。如果我改用while(a=a);,循环就可以了。怎么了?

3 个答案:

答案 0 :(得分:1)

完全与您的问题无关,但我将此作为答案发布,因为由于格式限制而难以在评论中写这个。

以下代码(虽然除了getchar问题之外是正确的)看起来好像{}之间的部分是for循环的一部分,因为;很容易被遗漏而{{1}这里没有必要。

{}

写这个就像这样:

for( ; c <= n; a = a*c, c = c +5);
{
  printf("The result is %d\nDo you want do it again? (Type 'Y' for yes and 'N' for no)", a);
  ch = getchar();
}

这使得循环有意清空更明显。

答案 1 :(得分:1)

首先是那些指向空循环的人......';'分号...它的目的是......

其次我提供了一个替代方案,它将解决目的: -

 #include <stdio.h>
int main()
{
    int n, a = 1, c = 5;
    char ch;
    do
    {
        printf("\nType the last number of the series 5 * 10 * 15 * ... * N:");
        scanf("%d", &n);
        for( ; c <= n; a = a*c, c = c +5);
        printf("%d\nthe series is",a);
        printf("The result is %d\nDo you want do it again? (Type 'Y' for yes and 'N' for no)", a);
        ch=getch();

    }
    while(ch!='n');
    return 0;
}

这将做我认为你想做的事情...... 另外我知道getch()和getchar()之间有区别,但在这里我只是为他提供了另一种解决方案......将这段代码粘贴到编译器上它会起作用

答案 2 :(得分:0)

问题的实际答案:

您的代码应该是这样的:

#include <stdio.h>

int main()
{
    int n, a, c;
    char ch;
    do
    {
        printf("Type the last number of the series 5 * 10 * 15 * ... * N:");
        scanf("%d", &n);
        getchar();   // absorb extra \n key from scanf, seem note below

        //   |< initialize a to 1 here, a needs to start from 1 each time
        //   |      |< initialize c to 5 here, c needs to start from 5 each time
        for (a = 1, c = 5 ; c <= n; a = a * c, c = c + 5)
        {
        }

        printf("The result is %d\nDo you want do it again? (Type 'Y' for yes and 'N' for no)", a);
        ch = getchar();
    }
    while (ch == 'y');

    return 0;
}

注意: scanf在输入缓冲区中留下一个额外的\n,它被孤独的getchar();吸收。如果没有单独的getchar();\n会被c = getchar();吸收,从而将\n放入ch

相关问题