如何将while循环转换为do-while循环
How to turn a while loop into a do while loop?
我有这个:
#include <iostream>
using namespace std;
int main()
{
char ch, max = 0;
int n = 0;
cout << "Enter number of characters! :";
cin >> n;
cout << "Enter the number";
while (n>0)
{
cin >> ch;
if(max<ch)
max = ch;
n=n-1;
}
cout << "max is : " << max;
}
我正试图把它变成一个边做边做的循环——这是我所拥有的:
int main()
{
char ch, max = 0;
int n = 0;
cout << "enter character";
cin >> n;
cout << "enter two";
cin >> ch;
do
(max<ch);
while
(max = ch);
(n>0);
n= n - 1;
cout << "max is : " << max;
}
我该如何解决这个问题?
使用提取器后,第一个程序需要检查EOF或其他故障:
#include <iostream>
using namespace std;
int main()
{
char ch, max = 0;
int n = 0;
cout << "Enter number of characters: ";
cin >> n;
cout << "Enter the number: ";
while (n > 0 && cin)
{
if (cin >> ch && max < ch)
max = ch;
n = n - 1;
}
cout << "max is : " << max << endl;
return 0;
}
我注意到,除了提示中的提示之外,代码中没有任何内容强制执行"it is a number"。此外,大多数让用户计算计算机可以计算的东西的界面都是被误导的。
将代码转换为使用do ... while
循环没有什么意义,但如果必须这样做,那么它最终看起来像:
#include <iostream>
using namespace std;
int main()
{
char ch, max = 0;
int n = 0;
cout << "Enter number of characters: ";
cin >> n;
cout << "Enter the number: ";
if (n > 0 && cin)
{
do
{
if (cin >> ch && max < ch)
max = ch;
n = n - 1;
} while (n > 0 && cin);
}
cout << "max is : " << max << endl;
return 0;
}
注意,出现在while
循环顶部的条件现在是单独的if
条件,并在do ... while (...)
条件中重复。仅此一点就告诉您do ... while
在这里是不合适的;如果有工作要做,您只想通过循环,但do ... while
循环无论如何都会强制您通过一次循环。
while (test) block;
相当于
if (test) {
do block
while (test);
}
所以你的while循环会变成
if (n>0) {
do {
cin >> ch;
if(max<ch)
max = ch;
n=n-1;
} while (n>0);
}
相关文章:
- 将手写循环转换为标准库调用
- 从基于迭代器的for循环转换后,如何在map::find()中调用方法
- 如何将python的for循环转换为c++
- 将 NumPy 切片循环转换为C++
- 我想将这些循环转换为递归.是否可以将这些循环转换为递归
- 如何在C++中将基本嵌套循环转换为递归循环
- 如何将循环转换为递归
- 如何将 c++ 中的 for 循环转换为汇编程序
- 将多个循环转换为一个递归
- 将此 C++ for 循环转换为汇编语言
- 将while循环转换为等效的for循环
- 正在将for循环转换为OpenMP
- 将 while 循环转换为 do while 循环
- 在数组的每个元素中存储一个值:将C do{}while循环转换为MIPS asm
- 从嵌套的 for 循环转换为嵌套的 while 循环时出现问题
- 将C++ FOR循环转换为德尔福
- 将简单的for循环转换为while循环
- 将do-while循环转换为while循环
- 将while循环转换为for循环会导致无限循环
- 在C++中将 FOR 循环转换为 DO WHILE 循环