我不想在最后一个数字/值之后使用逗号,我该如何删除它(c ++,loop)

时间:2017-11-04 05:25:35

标签: c++ loops comma

所以,我朋友的程序应该找到Number of Multiplicative of Number然后用数字之间的逗号打印出来。而不是最后一个。

int a;
int b;

cout<< "First Number = ";
cin>>a;
cout<< "Last Number = ";
cin>>b;

if(a<=b)
{
    for(a;a<=b;a++)
    {
        if(a%3 == 0 && a%2 != 0)
        {   
            cout<<a;
        }
        if(a<b && a%3==0 && a%2 != 0)
        {
            cout<< " , ";
        }
        else if(a==b)
        {
            cout<< ".";
        }
    }
}

在我输入

之后

a = 1

b = 20

这是我的预期

  

3,9,15。

这就是我实际得到的

  

3,9,15,。

以前,希望你们明白

1 个答案:

答案 0 :(得分:1)

我会做这样的事情:

char const* sep = ""; // item separator (nothing to begin with)

for(a;a<=b;a++)
{
    if(a%3 == 0 && a%2 != 0)
    {   
        cout << sep << a; // output the separator before the next value
        sep = ", "; // now change it to a comma
    }
}

cout << "."; // finish with a full stop