0
为什么我的if语句没有按预期工作 - if((l1%PrimeArr [l2])== 0)。以下是我所编码的内容 -打印所有素数直到N
/* Find all prime numbers<=N */
# include<stdio.h>
#define SIZE 100
void main()
{
int PrimeArr[SIZE];
int number;
int primeIndex=2; // 2 for 2 and 3 in the array
int l1; // loop counter 1
int l2; // loop counter 2
int l3; // loop counter 3
// 1. 2 is the only even prime number, save this in PrimeArray
PrimeArr[0]=2;
// 2. 3 is first odd prime number, save this in PrimeArray too.
PrimeArr[1]=3;
// 3. ask user uptil which number he want primes.
printf("\n Enter your number:");
scanf("%d",&number);
// 4. for numbers 4 to N if number P is divisible by all prime numbers less than P
for(l1=4;l1<=number;l1++){
for(l2=0;l2<primeIndex;l2++)
{
// 4.1 if yes, then p is composite
if((l1 % PrimeArr[l2]) == 0)
break; /* found out that the number is composite so let's get out of this loop to avoid unnecessary division */
else
{
//4.2.1 save this prime in prime array
PrimeArr[primeIndex++]=l1;
}
}
}
// display your prime array.
for(l3=0;l3<primeIndex;l3++)
printf("%d ",PrimeArr[l3]);
}
基本上当它到达内部循环时,if被忽略。 我想要做的是 - “如果数字可以被数组中的任何素数整除,则打破当前循环”,但它总是被忽略,并且控制始终在else中。
经过测试,如果即使在线编译器工作,你有逻辑错误的想法。 – koper89