用c++计算1-1/2+1/3-1/4+1/5+…+(-1)ⁿ⁻¹1/n
时间: 2023-11-18 22:04:42 浏览: 122
C++ 类1-1/2+2/3-3/4+...+(n-1)/n
以下是用C++计算1-1/2+1/3-1/4+1/5+…+(-1)ⁿ⁻¹1/n的代码:
```c++
#include <iostream>
using namespace std;
int main() {
int n;
double sum = 0;
cout << "请输入n的值:";
cin >> n;
for (int i = 1; i <= n; i++) {
if (i % 2 == 1) {
sum += 1.0 / i;
} else {
sum -= 1.0 / i;
}
}
cout << "结果为:" << sum << endl;
return 0;
}
```
阅读全文