我的代码是这样的我只想将我的do-while循环转换为for循环或while循环我该怎么做。程序的要点是反转输入的单词。就像你输入abc一样,它将输出为cba。
int main()
{
while (i < --length - 1);
cout << word << endl;
return 0;
}
答案 0 :(得分:2)
将while循环转换为for循环的传统方法采用以下形式:
// While loop
int i = 0;
while( i < n ) {
// Amazing things happen here
i++;
}
// Equivalent for loop
for( int i = 0; i < n; i++ ) {
// Amazing things still happen here
}
因此,应用于您的代码看起来像:
char ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
for( int i = 0, length = word.length(); i < --length - 1; i++ ) {
char ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
}
请注意,由于do-while循环在测试之前执行循环体,我不得不将循环体的一个副本放在前面。为了避免必须更新代码的两个不同副本,您可能需要将循环体提取到函数中,然后在循环前和循环体中调用该函数。
对于while循环版本:
int i = 0, length = word.length();
char ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
while( ++i < --length ) {
char ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
}
答案 1 :(得分:0)
另一种选择是,它不会对0或1大小的字符串做任何事情:
int length = word.length();
if (length > 1)
{
int i = 0;
char ch;
while (i < length)
{
ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
i++;
length--;
}
}
对于版本:
int length = word.length();
if (length > 1)
{
char ch;
for(int i = 0; i < length; i++, length--)
{
ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
}
}