简体   繁体   English

将 for 循环转换为 for 循环执行 while 循环

[英]Convert for to for loop to do while loop

I'm trying to convert this for loop to a do while loop and keep it a 7 x 7 matrix我正在尝试将此for 循环转换do while 循环并将其保持为7 x 7矩阵

For loop to print the number 7 x 7 : For 循环打印数字7 x 7

for (int height = 0; height < 7; height++){
    cout << numberMatrix[height][digitOne] << " ";
    cout << numberMatrix[height][digitTwo] << " ";
    cout << numberMatrix[height][digitThree] << " ";
    cout << endl;
}

Right output:右输出:

在此处输入图片说明

Here is my code after converting but it doesn't come out right.这是我转换后的代码,但结果不正确。

For loop to print the number 7 x 7 : For 循环打印数字7 x 7

 int height = 0;
    while (height < 7) {
        cout << numberMatrix[height][digitOne] << " ";
        cout << numberMatrix[height][digitTwo] << " ";
        cout << numberMatrix[height][digitThree] << " ";
        height++;
    }
}

Wrong output:错误输出:

在此处输入图片说明

In this case you should use while/for loop.在这种情况下,您应该使用 while/for 循环。 While loop should be used only when you need at least once loop should be evaluated even if condition is false.仅当您需要至少一次循环时才应使用 while 循环,即使条件为假。

Still you can try this do-while :你仍然可以试试这个do-while

int height = -1;
do{
    if(height > 0){
        cout << numberMatrix[height][digitOne] << " ";
        cout << numberMatrix[height][digitTwo] << " ";
        cout << numberMatrix[height][digitThree] << " ";
        cout << endl;
    }
    height++;
}while( height < 7);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM