
在现代编程语言中,我们同时使用有符号数和无符号数。对于有符号数,它们可以是正数、负数或零。为了表示负数,系统使用2的补码方法存储数字。在本文中,我们将讨论如何在C++中确定给定的数字是正数还是负数。
使用if-else条件进行检查
基本的符号检查可以通过使用 if else 条件来完成。 if-else 条件的语法如下 -
语法
if{ perform action when condition is true } else { perform action when condition is false }
算法
确定正数或负数的算法如下所示−
婚纱影楼小程序提供了一个连接用户与影楼的平台,相当于影楼在微信的官网。它能帮助影楼展示拍摄实力,记录访客数据,宣传优惠活动。使用频率高,方便传播,是影楼在微信端宣传营销的得力助手。功能特点:样片页是影楼展示优秀摄影样片提供给用户欣赏并且吸引客户的。套系页是影楼根据市场需求推出的不同套餐,用户可以按照自己的喜好预定套系。个人中心可以查看用户预约的拍摄计划,也可以获取到影楼的联系方式。
立即学习“C++免费学习笔记(深入)”;
- 输入一个数字n
- 如果 n
- 以负数形式返回 n
- 否则
- 返回正数 n
示例
#includeusing namespace std; string solve( int n ) { if( n < 0 ) { return "Negative"; } else { return "Positive"; } } int main() { cout << "The 10 is positive or negative? : " << solve( 10 ) << endl; cout << "The -24 is positive or negative? : " << solve( -24 ) << endl; cout << "The 18 is positive or negative? : " << solve( 18 ) << endl; cout << "The -80 is positive or negative? : " << solve( -80 ) << endl; }
输出
The 10 is positive or negative? : Positive The -24 is positive or negative? : Negative The 18 is positive or negative? : Positive The -80 is positive or negative? : Negative
使用三元运算符进行检查
我们可以通过使用三元运算符来删除if-else条件。三元运算符使用两个符号‘?’和‘:’。算法是相似的。三元运算符的语法如下所示 −
语法
? :
示例
#includeusing namespace std; string solve( int n ) { string res; res = ( n < 0 ) ? "Negative" : "Positive"; return res; } int main() { cout << "The 56 is positive or negative? : " << solve( 56 ) << endl; cout << "The -98 is positive or negative? : " << solve( -98 ) << endl; cout << "The 45 is positive or negative? : " << solve( 45 ) << endl; cout << "The -158 is positive or negative? : " << solve( -158 ) << endl; }
输出
The 56 is positive or negative? : Positive The -98 is positive or negative? : Negative The 45 is positive or negative? : Positive The -158 is positive or negative? : Negative
结论
在C++中检查给定的整数是正数还是负数是一个基本的条件检查问题,我们检查给定的数字是否小于零,如果是,则该数字为负数,否则为正数。这可以通过使用 else-if 条件扩展到负、零和正检查。通过使用三元运算符可以使用类似的方法。在本文中,我们通过一些示例讨论了它们。









