编写一个程序exp1-2.cpp,对于1∽n的每个整数n,输出log2n、√n、n、nlog2n、n2、n3、 2n和 n!的值。
时间: 2024-11-25 16:12:52 浏览: 22
编写这样一个程序需要使用C++语言,并利用一些数学函数库如cmath来进行计算。以下是一个简单的`exp1-2.cpp`程序示例:
```cpp
#include <iostream>
#include <cmath> // 引入math库,用于log2, sqrt等函数
// 定义主函数
int main() {
int n;
std::cout << "请输入一个正整数n (1 <= n): ";
std::cin >> n;
// 确保输入的是正整数
if(n <= 0) {
std::cerr << "错误: 输入的数值必须大于0.\n";
return 1;
}
// 计算并输出各个表达式的值
double log2_n = log2(n);
double sqrt_n = sqrt(n);
double n_log2_n = n * log2_n;
double n_squared = n * n;
double n_cubed = n * n * n;
double power_of_2 = pow(2, n);
unsigned long long factorial = 1;
for(int i = 1; i <= n; ++i) {
factorial *= i;
}
std::cout << "log2(" << n << ") = " << log2_n << "\n";
std::cout << "sqrt(" << n << ") = " << sqrt_n << "\n";
std::cout << n << " * log2(" << n << ") = " << n_log2_n << "\n";
std::cout << n << "^2 = " << n_squared << "\n";
std::cout << n << "^3 = " << n_cubed << "\n";
std::cout << "2^" << n << " = " << power_of_2 << "\n";
std::cout << "n! (" << n << "!)" << " = " << factorial << "\n";
return 0;
}
```
当你运行这个程序时,它会提示用户输入一个正整数n,然后依次计算并显示每个表达式的值。
阅读全文