#include<stdio.h>

#include<conio.h>

void main()
{
    int m,a,i,b;

    printf("Enter the number upto which the prime number is to be displayed:");
    scanf("%d",&m);

    for(a=1;a<=m;a++)
    {
        for(i=1;i<=a;i++)
        {
            if(a%i==0)
            {
                b++;
            }
        }
        if(b==2)
        {
            printf("\t%d",a);
        }
    }
    getch();
}

最佳答案

在代码的开头和循环内初始化b

#include<stdio.h>

#include<conio.h>

void main()
{
    int m,a,i,b=0; // initialize b

    printf("Enter the number upto which the prime number is to be displayed:");
    scanf("%d",&m);

    for(a=1;a<=m;a++)
    {
        for(i=1;i<=a;i++)
        {
            if(a%i==0)
            {
                b++;
            }
        }
        if(b==2)
        {
            printf("\t%d",a);
        }

        b=0; // re-initialize
    }
    getch();
}

关于c - 为什么嵌套的“for”循环在下面的程序中不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25356607/

10-11 23:08
查看更多