c++编写程序计算sum=1-1/2+1/4-1/8……
时间: 2023-11-23 08:07:13 浏览: 97
C++式子n^1+n^2+n^3+……+n^10计算
以下是C++编写程序计算sum=1-1/2+1/4-1/8……的代码:
```c++
#include <iostream>
using namespace std;
int main() {
int n;
float sum = 1.0, temp = 1.0;
cout << "请输入一个整数n:";
cin >> n;
for (int i = 1; i <= n; i++) {
temp /= 2;
if (i % 2 == 0) {
sum += temp;
} else {
sum -= temp;
}
}
cout << "sum=" << sum << endl;
return 0;
}
```
阅读全文