首页 > 文章列表 > C++程序检查一个数是正数还是负数

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

检查数正负判断
498 2023-09-09

在现代编程语言中,我们同时使用有符号数和无符号数。对于有符号数,它们可以是正数、负数或零。为了表示负数,系统使用2的补码方法存储数字。在本文中,我们将讨论如何在C++中确定给定的数字是正数还是负数。

使用if-else条件进行检查

基本的符号检查可以通过使用 if else 条件来完成。 if-else 条件的语法如下 -

语法

if <condition> {
   perform action when condition is true
}
else {
   perform action when condition is false
}

算法

确定正数或负数的算法如下所示−

  • 输入一个数字n
  • 如果 n < 0,则
  • 以负数形式返回 n
  • 否则
  • 返回正数 n

示例

#include <iostream>
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? : Positive
The -24 is positive or negative? : Negative
The 18 is positive or negative? : Positive
The -80 is positive or negative? : Negative

使用三元运算符进行检查

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

语法

<condition> ? <true case> : <false case>

示例

#include <iostream>
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? : 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 条件扩展到负、零和正检查。通过使用三元运算符可以使用类似的方法。在本文中,我们通过一些示例讨论了它们。