如何在C ++中打印带有前缀+的正数 [英] How to print positive numbers with a prefix + in C++

查看:75
本文介绍了如何在C ++中打印带有前缀+的正数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++中是否有任何方法可以打印整数及其符号?默认情况下,如果数字为负,我们将打印一个-符号.以同样的方式,我们可以在正数之前得到+.

Is there any way to print the integer along with its sign in c++...i.e. by default if the number is negative we would get a - sign printed. In the same way can we get + before the positive numbers.

int x=-1;
cout<<"x="<<x;

给出输出x=-1

但是,..

int x=+1;
cout<<"x="<<x;

将输出显示为x=1,但如何将其打印为x=+1

gives output as x=1 but how do i get it printed as x=+1

我知道我们可以通过对<> 5和x <0;使用if-else来解决问题,但是不使用if-else可以在c ++中进行打印的任何直接方式

I know we can take cases by using if-else for x>0 and x<0;..but without using the if-else is there any direct way of printing in c++

推荐答案

使用 std::showpos :

int x = 1;
std::cout << "x=" << std::showpos << x;

这篇关于如何在C ++中打印带有前缀+的正数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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