C++程序检查一个数是正数还是负数

c++程序检查一个数是正数还是负数

在现代编程语言中,我们同时使用有符号数和无符号数。对于有符号数,它们可以是正数、负数或零。为了表示负数,系统使用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

示例

#include using 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? : PositiveThe -24 is positive or negative? : NegativeThe 18 is positive or negative? : PositiveThe -80 is positive or negative? : Negative

使用三元运算符进行检查

我们可以通过使用三元运算符来删除if-else条件。三元运算符使用两个符号‘?’和‘:’。算法是相似的。三元运算符的语法如下所示 −

语法

 ?  : 

示例

#include using 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? : PositiveThe -98 is positive or negative? : NegativeThe 45 is positive or negative? : PositiveThe -158 is positive or negative? : Negative

结论

在C++中检查给定的整数是正数还是负数是一个基本的条件检查问题,我们检查给定的数字是否小于零,如果是,则该数字为负数,否则为正数。这可以通过使用 else-if 条件扩展到负、零和正检查。通过使用三元运算符可以使用类似的方法。在本文中,我们通过一些示例讨论了它们。

以上就是C++程序检查一个数是正数还是负数的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1445014.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月17日 22:06:13
下一篇 2025年12月14日 09:25:55

发表回复

登录后才能评论
关注微信