如果(质数)有效,最后一个语句怎么样?
问题描述:
#include<stdio.h>
main()
{
int i, prime, u, n;
scanf("%d",&u);
for(n=2; n<u; n++)
{
prime = 1;
for(i=2; i<n; i++)
{
if(n%i == 0)
{
prime = 0;
break;
}
}
if(prime)
printf("%d ",n); //avoid '\b' and use space after %d
}
}
我尝试过:
我不明白声明是如何工作的告诉我它是如何工作的
What I have tried:
I don't understand how the statement works tell me how it works
答
在C中,没有的概念
和false
因为有许多(更现代的)语言。
相反,任何非零的值都是被认为是真,任何零值都被视为假。
所以当你在循环中设置变量prime
时,你可以在循环外测试它并找出发生了什么。
如果你将prime
设置为0,那么你说这不是素数所以你不会打印这条消息。
但是......无论你从哪里得到这些代码,检查质数都是一种非常糟糕的方式:它检查一下很多相同的数字和再次。
你可能想要考虑 Eratosthenes的筛选 [ ^ ]解决方案,因为您的解决方案将变得非常慢,因为u
变大。
In C, there is no concept oftrue
andfalse
as there is in many (more modern) languages.
Instead, any value which is non-zero is considered "true" and any value which is zero is considered "false".
So when you set the variableprime
inside your loops, you can test it outside the loops and find out what happened.
If you setprime
to 0, then you are saying "this is not a prime number" so you will not print the message.
But ... wherever you go that code from, it's a pretty poor way to check for primes: it checks a heck of a lot of the same numbers over and over again.
You might want to consider a Sieve of Eratosthenes[^] solution instead as your solution will get very slow asu
gets larger.