我怎么摆脱最后一个逗号?

时间:2014-11-11 22:09:18

标签: c arrays loops

   int main(){
   int
      i,
      number[50],
      num;
   printf("Please enter a number:\n");
   scanf("%d", &num);
   for (i = 0; i < num; i++){
   printf("%d: ", i+1);
   scanf("%d", &number[i]);
   }

   printf("You've entered: ");
   for (i = 0; i < num; i++){
      printf("%d, ", number[i]);

   }
   }

如果我输入如下5个随机数,我似乎无法得到这个输出:

“请输入一个数字: 您输入了:1,2,32,44和45“

3 个答案:

答案 0 :(得分:1)

printf("You've entered: ");
for (i = 0; i < num; i++){
   if(num > 1 && i == num-1)
       printf(" and ");
   else if(i)
       printf(", ");
   printf("%d", number[i]);
}
printf("\n");

答案 1 :(得分:1)

您可以编辑最终的for循环,如下所示:

printf("You've entered: ");
for(i=0;i<num-2;i++)
  printf("%d",number[i]);
printf("%d and %d\n",number[i],number[i+1]);

答案 2 :(得分:0)

   printf("You've entered: ");
   for (i = 0; i < num; i++){
      printf("%d%s", number[i], (i == num-1) ? "" : ",");

   }