【问题标题】:Convert for to for loop to do while loop将 for 转换为 for 循环以执行 while 循环
【发布时间】:2016-10-04 08:48:39
【问题描述】:

我正在尝试将此 for 循环 转换为 do while 循环 并将其保留为 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;
}

右输出:

这是我转换后的代码,但结果不正确。

For循环打印数字7 x 7

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

错误的输出:

【问题讨论】:

  • cout &lt;&lt;endl; 你在while循环中忘记了这一行
  • 请不要张贴图片,复制/粘贴文本输出
  • 这两个代码sn-ps是等价的(除了while中缺少cout&lt;&lt;endl
  • 这是一个while循环。 do while 循环的结尾有条件,并且必须始终至少执行一次。因此,如果允许为空或 null 的情况,它不能轻易替换 for。

标签: c++ loops for-loop do-while


【解决方案1】:

在这种情况下,您应该使用 while/for 循环。 仅当您需要至少一次循环时才应使用 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);

【讨论】:

  • 为什么是int height = -1;?它不会在第一次迭代中打印任何内容,并且您正在添加一个额外的无用 if
猜你喜欢
  • 2018-02-22
  • 2017-04-26
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 2020-06-20
相关资源
最近更新 更多