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条件扩展到负数、零和正数的检查。可以使用三元运算符采用类似的方法。在这篇文章中,我们用几个例子讨论了这两种方法。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP