c - 打印列表时省略最后一个逗号

标签 c list csv formatting

我想显示两个数字之间的质数,例如 2,5,7,11 但显示是这样的2,5,7,11,多了一个“,”。

#include <stdio.h>
int main()
{
   int n1,n2,f,i,j;

   scanf("%d %d", &n1, &n2);

   for(i=n1; i<n2; ++i)
   {
      f=0;
      for(j=2; j<=i/2; ++j)
      {
         if(i%j==0)
         {
            f=1;
            break;
         }
      }
      if(f==0)
        if(i!=1)
         printf("%d,",i);
   }
   return 0;
}

最佳答案

回答问题但不考虑@Bathsheeba 提出的观点:

#include <stdio.h>

int main()
{
   int n1,n2,f,i,j;

   scanf("%d %d", &n1, &n2);

   int itemCount = 0;  // NEW

   for(i=n1; i<n2; ++i)
   {
      f=0;
      for(j=2; j<=i/2; ++j)
      {
         if(i%j==0)
         {
            f=1;
            break;
         }
      }

      if (f == 0  &&  i != 1)  // TESTS COMBINED
      {
        if (itemCount++ > 0) putchar(',');  // HERE
        printf("%d",i);                     // COMMA REMOVED
      }
   }
   printf("\n"); // newline at the end
   return 0;
}

在添加逗号后真正删除逗号的唯一方法是在运行时构建缓冲区 - 这是一种合理的方法 - 所以这里我们必须只在需要时才生成逗号,首先但第一项。

关于c - 打印列表时省略最后一个逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58862062/

相关文章:

python - 如果第一个元组元素匹配,如何合并列表中的两个元组?

c - 如何在 ANSI C 中进行浮点乘法?

c - 在结构体数组中搜索字符串

c++ - 在 C++ 中随机排列字符串列表

c# - 使用 Linq 从另一个具有匹配值的列表更新列表

python - 研究 Pandas DataFrame 中的不同数据类型

c - .lib 中的符号在 .so 中不存在

c - 理解 main 的不常见参数

python - 如何在 Python 中循环两次列表

javascript - 如何使用 javascript 生成正确的 csv 文件格式