C++用whlie循环,1.求s=1+2+3+4+.....+10 2.求s=1+1/2+1/3+.....1/100的程序
时间: 2023-11-11 11:03:54 浏览: 134
C语言实现求1+2+3+……+100的和,要求分别用while、do while、for循环实现。.txt
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
阅读全文