2011-09-19 52 views
-2

我有这样的:如何将while循环变成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"; 
    while (n>0) 
    { 
     cin >> ch; 
     if(max<ch) 
      max = ch; 
     n=n-1; 

    } 
    cout << "max is : " << max; 
} 

我试图把它变成一个do while循环 - 这是我有:

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

我该如何解决这个问题?

+6

是您的实际代码还是发布时发生错误。 –

+2

你想做什么? – cpx

+2

为什么你想把它变成一个'do {...} while(condition)'循环?如果用户为“字符数”输入零,该怎么办? –

回答

2
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); 
} 
4

第一个程序需要检查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; 
} 

我注意到,在代码中没有任何东西强制提示'它是一个数字'。此外,大多数使用户对计算机可以计数的东西进行计数的接口都被误导了。

有一个在转换使用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循环强制你循环一次。