关模拟初学c++顺序结构算数运算的程序出10道
时间: 2024-12-20 22:14:57 浏览: 12
当你初学 C++ 语言并想要练习基本的顺序结构和算术运算时,可以编写一些简单的程序来解决数学题目。这里提供10个例子:
1. 计算两个整数的加法:
```cpp
#include <iostream>
int main() {
int a = 5;
int b = 3;
int sum = a + b;
std::cout << "The sum of " << a << " and " << b << " is " << sum << std::endl;
return 0;
}
```
2. 减法运算:
```cpp
int main() {
int num1 = 10;
int num2 = 4;
int difference = num1 - num2;
std::cout << "The difference between " << num1 << " and " << num2 << " is " << difference << std::endl;
return 0;
}
```
3. 乘法操作:
```cpp
int main() {
double x = 2.5;
double y = 3.7;
double product = x * y;
std::cout << "The product of " << x << " and " << y << " is " << product << std::endl;
return 0;
}
```
4. 除法演示:
```cpp
#include <iostream>
double safe_division(double numerator, double denominator) {
if (denominator == 0) {
std::cerr << "Error: Division by zero!" << std::endl;
return 0; // 或者抛异常
}
return numerator / denominator;
}
int main() {
double divisor = 5.0;
double dividend = 2.0;
double quotient = safe_division(dividend, divisor);
std::cout << "The quotient of " << dividend << " divided by " << divisor << " is " << quotient << std::endl;
return 0;
}
```
5. 整数取模运算:
```cpp
#include <iostream>
int main() {
int num = 15;
int divisor = 7;
int remainder = num % divisor;
std::cout << "The remainder when " << num << " is divided by " << divisor << " is " << remainder << std::endl;
return 0;
}
```
6. 幂运算:
```cpp
#include <cmath>
int main() {
double base = 2;
int exponent = 3;
double result = pow(base, exponent);
std::cout << "The result of " << base << "^" << exponent << " is " << result << std::endl;
return 0;
}
```
7. 求平均值:
```cpp
#include <vector>
int main() {
std::vector<int> numbers {1, 2, 3, 4, 5};
double average = 0;
for (int i : numbers) {
average += i;
}
average /= numbers.size();
std::cout << "The average of the numbers is " << average << std::endl;
return 0;
}
```
8. 最大值和最小值比较:
```cpp
#include <algorithm>
int main() {
int array[] = {9, 2, 7, 5, 1};
int max_num = *std::max_element(array, array + sizeof(array) / sizeof(array[0]));
int min_num = *std::min_element(array, array + sizeof(array) / sizeof(array[0]));
std::cout << "Max number: " << max_num << ", Min number: " << min_num << std::endl;
return 0;
}
```
9. 计算阶乘:
```cpp
#include <iostream>
unsigned long long factorial(int n) {
if (n == 0 || n == 1) return 1;
else return n * factorial(n - 1);
}
int main() {
int num = 5;
unsigned long long fact = factorial(num);
std::cout << "Factorial of " << num << " is " << fact << std::endl;
return 0;
}
```
10. 判断奇偶性:
```cpp
int main() {
int num = 17;
if (num % 2 == 0) {
std::cout << num << " is even." << std::endl;
} else {
std::cout << num << " is odd." << std::endl;
}
return 0;
}
```
阅读全文