我编写了这段代码,打印出1和输入值之间的所有素数:
#include <stdio.h>
#include <conio.h>
int main()
{
//Declaration of variables:
int N, i, j, isPrime, n;
// Ask user for input the upper limit for the generation of primes (N)
printf("Enter the value of N\n");
scanf("%d",&N);
if (N==1){
printf("There are no prime numbers before 1. Please recompile. \n" ); //print out an error if
// 1 is inputted as the upper limit for the generation of primes.
}
/* For every number between 2 to N, check whether it is prime number or not */
else
printf("The primes between 1 and %d are: ", N);
for(i = 2; i <= N; i++){
isPrime = 0;
/* Check whether i is prime or not */
for(j = 2; j <= i/2; j++){
/* Check If any number between 2 to i/2 divides I completely If it divides, the numebr cannot be a prime. */
if(i % j == 0){
isPrime = 1;
break;
}
}
// print out the primes if the conditions are met
if(isPrime == 0 && N != 1)
printf("%d, ", i);
}
return 0;
}
它工作得很好,但我在每个值后面都有一个逗号,包括最后一个。我想删除刚才从最后一个显示的逗号。
非常感谢你。
最佳。
答案 0 :(得分:2)
由于确定循环的哪个迭代是最后一个有点困难,可以在输出之前将逗号放在输出之前,而忽略第一个逗号如下,为简洁起见删除了注释。
int isFistIteraion = 0;
for(i = 2; i <= N; i++)
{
isPrime = 0;
for(j = 2; j <= i/2; j++){
if(i % j == 0){
isPrime = 1;
break;
}
}
if(IsPrime == 0 && N != 1){
if (0 == isFirstIteration){
isFirstIteraion = 1;
printf("%d", i);
} else {
printf(", %d", i);
}
}
}