C++用whlie循环,1.求s=1+2+3+4+.....+10 2.求s=1+1/2+1/3+.....1/100的程序
时间: 2023-11-11 20:03:54 浏览: 140
1. 求s=1+2+3+4+.....+10的程序:
```c++
#include <iostream>
using namespace std;
int main() {
int i = 1, s = 0;
while (i <= 10) {
s += i;
i++;
}
cout << "s = " << s << endl;
return 0;
}
```
输出结果为:s = 55
2. 求s=1+1/2+1/3+.....1/100的程序:
```c++
#include <iostream>
using namespace std;
int main() {
int i = 1;
double s = 0;
while (i <= 100) {
s += 1.0 / i;
i++;
}
cout << "s = " << s << endl;
return 0;
}
```
输出结果为:s = 5.18738
相关问题
C++用whlie循环,1.求s=1+2+3+4+.....+10 2.求s=1+1/2+1/3+.....1/100
好的,我来回答你的问题。
1. 求s=1+2+3+4+.....+10 的代码如下:
```c++
int s = 0;
int i = 1;
while (i <= 10) {
s += i;
i++;
}
cout << "s = " << s << endl;
```
输出结果为:s = 55
2. 求s=1+1/2+1/3+.....1/100 的代码如下:
```c++
double s = 0;
int i = 1;
while (i <= 100) {
s += 1.0 / i;
i++;
}
cout << "s = " << s << endl;
```
输出结果为:s = 5.18738
C++while循环语句求: 1、s=1-2+3-4+5-…+n 2、s=1+2-3+4+5-6+7+…+n
以下是两种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;
}
```
阅读全文