簡體   English   中英

我不想在最后一個數字/值之后使用逗號,我該如何刪除它(c++,循環)

[英]I don't want a comma after the last number/value, how do i remove it (c++, loop)

所以,我朋友的程序應該找到數字三的乘數,然后在數字之間用逗號打印出來。 而不是最后一個。

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、.

我會做這樣的事情:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM