2016-12-04 101 views
1

我写了这个代码1和输入值之间打印出所有质数:如何从C中的输出中省略最终的逗号(,)?

#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; 
} 

它的伟大工程,但我得到一个逗号分隔每个值之后,包括最后一个。我想从最后一个显示的逗号中删除。

非常感谢您提前。

最好。

+2

通过印刷'2'第一,然后*预谋*逗号代替* *追加它 – StoryTeller

+0

'的printf( “%d”,,I)'的每个数字后写入一个逗号。你需要改变它。想想在纸上写出列表时要做什么,然后尝试将其转换为程序代码。 –

+1

知道'2'是一个素数,你可以从计算中跳过这个数字并打印'2',然后在后面的输出位置上逗号*之前*数字(oops类似于@StoryTeller)。 –

回答

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); 
     } 
    } 
}