编写一个程序exp1-2.cpP,对于1~n的每个整数n,输出l0gzn、Vn、n、nlogzn、n2、n3、2n和n!的值。
时间: 2025-04-19 13:47:02 浏览: 20
### 程序设计思路
为了编写这个程序 `exp1-2.cpp`,我们需要计算并输出一系列数学表达式的值。具体来说,对于给定的整数范围 `[1, n]` 中的每一个整数值,我们将分别求出:
- \( \log_2(n) \)
- \( \sqrt{n} \)
- \( n \)
- \( n \cdot \log_2(n) \)
- \( n^2 \)
- \( n^3 \)
- \( 2^n \)
- \( n! \)
由于涉及到对数函数、幂运算以及阶乘等复杂操作,我们可以利用 C++ 标准库中的 `<cmath>` 和自定义递归或迭代算法来完成这些任务。
#### 示例代码(C++)
```cpp
#include <iostream>
#include <iomanip> // for std::setw and std::setprecision
#include <cmath> // for log2, sqrt, pow functions
using namespace std;
// Function to calculate factorial iteratively.
long long factorial(int n) {
if (n <= 1) return 1;
long long result = 1;
for (int i = 2; i <= n; ++i) {
result *= i;
// Check for overflow in the factorial calculation
if(result <= 0){
cout << "Overflow occurred at factorial of " << n << endl;
exit(1);
}
}
return result;
}
void printValues(int n) {
const int maxN = 20; // Limiting output size due to large values beyond this point.
cout << setw(5) << "n"
<< setw(9) << "log2(n)"
<< setw(8) << "sqrt(n)"
<< setw(6) << "n"
<< setw(14) << "n*log2(n)"
<< setw(7) << "n^2"
<< setw(7) << "n^3"
<< setw(7) << "2^n"
<< setw(7) << "n!"
<< endl;
for (int i = 1; i <= min(maxN, n); ++i) {
double lgn = log2(i);
double sqrtn = sqrt(i);
double nlgn = i * lgn;
double nsqr = pow(i, 2);
double ncube = pow(i, 3);
double exp2 = pow(2, i);
cout << fixed << setprecision(2) // Set precision for floating-point numbers
<< setw(5) << i
<< setw(9) << lgn
<< setw(8) << sqrtn
<< setw(6) << i
<< setw(14) << nlgn
<< setw(7) << nsqr
<< setw(7) << ncube
<< setw(7) << exp2
<< setw(7) << factorial(i)
<< endl;
// Factorial grows very fast, so we limit the upper bound here
if(factorial(i) > LLONG_MAX / 10 || exp2 >= numeric_limits<double>::max()) break;
}
}
int main() {
int n;
while(true){
try{
cout << "请输入一个正整数n: ";
cin >> n;
if(cin.fail()){
throw runtime_error("输入错误");
}
if(n <= 0){
throw range_error("n应为大于零的整数!");
}else{
printValues(n);
break;
}
}catch(const exception& e){
cerr << "发生异常:" << e.what() << "\n";
cin.clear(); // 清除标志位
cin.ignore(INT_MAX,'\n'); // 清空缓冲区
continue;
}
}
return 0;
}
```
此段代码首先导入了必要的头文件,并定义了一个用于计算阶乘的辅助函数 `factorial()` 。然后,在主函数中提示用户输入一个上限 `n` ,并通过循环结构依次打印所需的所有列值至标准输出设备上。请注意,我们还添加了一些基本的数据验证机制以保证程序正常运行,同时限制最大显示行数以免溢出屏幕。
考虑到某些高次项如指数和阶乘增长速度极快可能导致数据超出类型表示范围的问题,这里也做了相应的处理措施避免出现未定义行为或不准确的结果展示。
阅读全文
相关推荐















