出10个c++算数运算符的使用程序
时间: 2024-12-20 20:15:01 浏览: 5
当然可以,这里列举十个常见的C++算术运算符及其在简单程序中的使用示例:
1. **加法** (+):
```cpp
int a = 5;
int b = 3;
int sum = a + b; // sum 现在是 8
cout << "Sum: " << sum << endl;
```
2. **减法** (-):
```cpp
int c = 10;
int difference = c - 7; // difference 现在是 3
cout << "Difference: " << difference << endl;
```
3. **乘法** (*):
```cpp
double num1 = 2.5;
double num2 = 4.0;
double product = num1 * num2; // product 现在是 10.0
cout << "Product: " << product << endl;
```
4. **除法** (/):
```cpp
float divisor = 8.0f;
float quotient = 16.0 / divisor; // quotient 现在是 2.0
cout << "Quotient: " << quotient << endl;
```
5. **取模** (%):
```cpp
int remainder = 9 % 4; // remainder 现在是 1
cout << "Remainder: " << remainder << endl;
```
6. **自增(++)** 和 **自减(--)**:
```cpp
int num = 5;
num++; // num 现在是 6
cout << "Incremented: " << num << endl;
num--; // num 现在是 5
cout << "Decremented: " << num << endl;
```
7. **求幂(**):
```cpp
long int base = 2;
int exponent = 3;
int power = pow(base, exponent); // power 现在是 8 (因为 2^3)
cout << "Power of 2: " << power << endl;
```
注意,`pow`是一个库函数,你需要包含 `<cmath>`。
8. **负数(-)**:
```cpp
double negNum = -5.5;
cout << "Negative number: " << negNum << endl;
```
9. **无理数运算**(比如 `sqrt` 或 `log` 需要用到 `<cmath>` 库):
```cpp
#include <cmath>
double radius = 4.0;
double area = M_PI * pow(radius, 2); // 使用 π 计算圆面积
cout << "Area: " << area << endl;
```
10. **浮点数比较** (例如三元运算符 `?:` 可能涉及比较):
```cpp
if (num1 > num2) {
cout << "First is greater" << endl;
} else {
cout << "Second is greater or equal" << endl;
}
```
阅读全文