首頁  >  文章  >  後端開發  >  C++程式檢查一個數是正數還是負數

C++程式檢查一個數是正數還是負數

WBOY
WBOY轉載
2023-09-12 15:09:031873瀏覽

C++程式檢查一個數是正數還是負數

在現代程式語言中,我們同時使用有符號數和無符號數。對於有符號數,它們可以是正數、負數或零。為了表示負數,系統使用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
  • 以負數形式傳回 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 條件來擴展到負、零和正檢查。透過使用三元運算子可以使用類似的方法。在本文中,我們透過一些範例討論了它們。

以上是C++程式檢查一個數是正數還是負數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除