C++while循环语句求: 1、s=1-2+3-4+5-…+n 2、s=1+2-3+4+5-6+7+…+n
时间: 2024-01-09 14:21:55 浏览: 83
编译原理课设while循环语句的识别c++
以下是两种C++ while循环语句求解的例子:
1. 求解 s = 1-2+3-4+5-...+n
```cpp
#include <iostream>
using namespace std;
int main() {
int n;
cout << "请输入n的值:";
cin >> n;
int i = 1;
int s = 0;
int sign = 1;
while (i <= n) {
s += i * sign;
sign = -sign;
i++;
}
cout << "s = " << s << endl;
return 0;
}
```
2. 求解 s = 1+2-3+4+5-6+7+...+n
```cpp
#include <iostream>
using namespace std;
int main() {
int n;
cout << "请输入n的值:";
cin >> n;
int i = 1;
int s = 0;
int sign = 1;
while (i <= n) {
s += i * sign;
sign = -sign;
i++;
if (i % 2 == 0) {
i++;
}
}
cout << "s = " << s << endl;
return 0;
}
```
阅读全文