gpt4 book ai didi

c - 如何从 C 中的输出中省略最后的逗号 (,)?

转载 作者:太空宇宙 更新时间:2023-11-04 02:32:54 28 4
gpt4 key购买 nike

我编写了这段代码来打印出 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;
}

效果很好,但我在每个值(包括最后一个值)后都有一个逗号。我想从最后一个逗号中删除逗号。

非常感谢您。

最好的。

最佳答案

因为确定循环的哪一次迭代是最后一次有点困难,可以将逗号放在输出的之前而不是之后并省略第一个逗号如下,为简洁起见,删除了评论。

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

关于c - 如何从 C 中的输出中省略最后的逗号 (,)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40963553/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com