如何在输出中用逗号分隔数字



我想找到给定范围内的素数。输出编号必须用逗号分隔。

#include <iostream>
using namespace std;
int main() 
{
int i,j,lower, upper;
cin >> lower;
cin >> upper;
for (i = lower + 1; i < upper; i++)
{
for  (j = 2; j < i; j++)
{
if (i % j == 0)
{
break;
}
}
if (j == i)
{
cout << i ;
cout << ",";
}
}
}

输入:11 20

输出必须为:13,17,19

但我的代码打印了一个额外的逗号,它不仅仅在数字之间。你能帮帮我吗?!

您可以将结果存储在向量中,这样您就可以准确地知道要打印多少数字,而不是立即打印结果。然后你用这种方式打印你的矢量:

std::vector result;
std::string output = "";
for (size_t i = 0; i < result.size(); ++i) // Notice the ++i, not i++
{
if (i != 0)
output += ", ";
output += result[i];
}

如果不想将结果存储在向量中,则可以将布尔firstResult定义为true(如果尚未打印昏迷(,然后在打印第一个结果时定义为false,并在数字之前打印昏迷。

int main() 
{
bool firstResult = true;
[...]
if (j == i)
{
if (!firstResult)
cout << ",";
firstResult = false;
cout << i ;
}
}

最新更新