如何将while循环转换为do-while循环

How to turn a while loop into a do while loop?

本文关键字:循环 转换 do-while while      更新时间:2023-10-16

我有这个:

#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);
}