打印列表时省略最后一个逗号
omitting last comma when printing a list
我想在两个数字之间显示质数,例如 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;
}
添加逗号后真正删除逗号的唯一方法是在运行时构建缓冲区 - 这是一种合理的方法 - 所以在这里我们只需要在需要时生成逗号,在除第一项之外的所有项之前。
我想在两个数字之间显示质数,例如 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;
}
添加逗号后真正删除逗号的唯一方法是在运行时构建缓冲区 - 这是一种合理的方法 - 所以在这里我们只需要在需要时生成逗号,在除第一项之外的所有项之前。