我已经创建了这个C程序,它应该告诉我1-25之间有多少素数,但是打印的每个数字都是素数。请帮忙
#include<stdio.h>
int main(void) {
int n = 1, counter = 0;
int i, flag = 0;
while ( n <= 25 )
{
for ( i = 2; i <= (n/2); i++ )
{
if (n%i == 0)
{
flag = 0;
}
}
if (flag == 0)
{
counter++;
printf("%d is Prime Number.\n", n);
}
else
{
printf("%d is not Prime Number.\n", n);
}
n++;
}
return 0;
}
答案 0 :(得分:5)
flag = 0;
您的旗帜始终为0
。进入1
循环
while
while ( n <= 25 ) {
flag = 1; //<-- here
for ( i = 2; i <= (n/2); i++ ) {
您也可以在细分中break
,仅用于效率
if (n%i == 0)
{
flag = 0;
break;
}
答案 1 :(得分:0)
您可以将代码用作
for ( i = 2; i <= sqrt(n); i++ )
{
if (n%i == 0)
{
flag = 0;
}
}
if (flag == 0)
{
counter++;
printf("%d is Prime Number.\n", n);
flag=1;
}
else
{
printf("%d is not Prime Number.\n", n);
}
n++;
使用sqrt()
代替n/2
程序会更有效率。