.在while和do-while循环中编写程序: 1+2+3... +20。c++做
时间: 2023-12-18 15:06:05 浏览: 36
使用while循环:
```c++
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int i = 1;
while (i <= 20) {
sum += i;
i++;
}
cout << "1+2+3+...+20 = " << sum << endl;
return 0;
}
```
使用do-while循环:
```c++
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int i = 1;
do {
sum += i;
i++;
} while (i <= 20);
cout << "1+2+3+...+20 = " << sum << endl;
return 0;
}
```
两种循环的输出结果都为:1+2+3+...+20 = 210。
相关问题
Do while语句语句编写in=2/1+3/2+4/3。
以下是使用do-while语句编写的代码,实现输入in=2/1, 3/2, 4/3的功能:
```c++
#include <iostream>
using namespace std;
int main() {
int numerator, denominator;
char slash;
do {
cout << "Enter a fraction in the format of 'numerator/denominator': ";
cin >> numerator >> slash >> denominator;
} while (numerator != 2 || denominator != 1 && numerator != 3 || denominator != 2 && numerator != 4 || denominator != 3);
cout << "You entered: " << numerator << "/" << denominator << endl;
return 0;
}
```
在这个程序中,我们使用do-while循环来要求用户输入一个分数,直到输入的分数是2/1、3/2或4/3为止。首先,我们定义了三个变量:numerator为分子,denominator为分母,slash为分数中的斜杠。然后我们在循环中使用cin语句来读取用户输入的分数,并且使用条件语句来检查是否输入了正确的分数。如果输入的分数不是2/1、3/2或4/3,循环将继续执行,要求用户重新输入分数。如果输入的分数是正确的,循环将结束,我们将输出用户输入的分数。
编写程序用do-while循环按公式e=1+1/1!+1/2!+1/3!+…+1/n!计算 e 的值(精度为 1e-6)。
好的,我可以帮你写一个C++的程序来计算e的值。以下是代码:
```c++
#include <iostream>
using namespace std;
int main() {
double e = 1.0, term = 1.0;
int n = 1;
do {
term /= n;
e += term;
n++;
} while (term >= 1e-6);
cout << "e = " << e << endl;
return 0;
}
```
程序中的变量`e`表示计算得到的e的值,`term`表示每一项的值,`n`表示当前计算的项数。程序使用do-while循环计算e的值,每次循环计算一项,并将其加入e中。当计算得到的一项小于1e-6时,循环结束,计算结束。最后程序输出计算得到的e的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)