如何在C ++中的最后一个数字/输出循环后删除逗号 [英] How do I remove comma after last number/output loop in C++

查看:517
本文介绍了如何在C ++中的最后一个数字/输出循环后删除逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我输入

a = 1

b = 20



我的输出总是:

3,9,15 ,.



但我想要的是:

3,9,15



PS:我的英文不好,我希望你们能理解

i只需要一个例子或解决方案



我尝试过:



when i input
a = 1
b = 20

my output is always :
"3 , 9 , 15 , ."

but what i wanted is :
"3 , 9 , 15."

PS : SOrry for my bad english, i hope you guys understand
i just need an example or solution to this program

What I have tried:

int a,b;

cout<< "Number 1 = ";
cin>>a;
cout<< "Number 2 = ";
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<< ".";
        }

推荐答案

您可以像这样编写if-else逻辑:

You could write the if-else logic like this :
if( ( a % 3 == 0 ) && ( a % 2 != 0 ) )
{
    cout << a;
    if( a == b )
        cout << ".";
    else
        cout << " , ";
}


首先,稍微分析一下:

'。'将始终打印并始终是最后一个。这意味着简化

First, a little analyze:
The '.' will be always printed and always be last. Which means simplification
if(a<=b)
{
    for(a;a<=b;a++)
    {
        if(a%3==0&&a%2!=0)
        {
            cout<<a;
            if(a<b)
            {
                cout<< " , ";
            }
        }
    }
    cout<< ".";
}



代码中的问题是无需打印 b

这个有很多解决方案

- 如果你在一个数字后打印逗号,你需要确保下一个数字要打印。

- 如果玩具在数字前打印逗号,你需要确保它不是第一个。


The problem in your code is that b will not necessary be printed.
There is many solution around this
- if you print the comma after a number, you need to make sure there will be a next number to print.
- if toy print the comma before a number, you need to make sure it is not the first.


谢谢你们,但我已经得到了我的解决方案



Thanks guys but i already got my solution to put

char const*sep = ""

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


这篇关于如何在C ++中的最后一个数字/输出循环后删除逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆