C++程式:判斷數字是正數還是負數
在現代程式語言中,我們使用有符號數和無符號數。對於有符號數,數字可以是正數、負數或零。為了表示負數,系統使用二進位制補碼方法儲存數字。在這篇文章中,我們將討論如何在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條件擴充套件到負數、零和正數的檢查。可以使用三元運算符采用類似的方法。在這篇文章中,我們用幾個例子討論了這兩種方法。
廣告