Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        3年前关闭。
                                                                                            
                
        
这是使用for循环的代码:

for (int i = 0; i < 3; i += 1) {
    for (int j = 0; j < 3; j += 1) {
        cout << "HI" << endl;
    }
}


这是我尝试用whiles代替它:

int i=0,j=0;
while(i < 3) {
    while(j < 3) {
        cout << "HI" << endl;
        j++;
    }
    i++;
}


就像我希望它们一样,for循环将输出“ HI” 9次。我不明白为什么while循环仅对内部表达式求值一次,而将“ HI”输出3次。

最佳答案

“ OMG,我想我明白了。我需要在每个外部while循环中重置j。”

是的,你是对的。内循环:

 for (int j = 0; j < 3; j += 1) {
        cout << "HI" << endl;
    }


在外循环的每次迭代中将j重置为零。

int i=0;
while(i < 3) {
    int j= 0;
    while(j < 3) {
        cout << "HI" << endl;
        j++;
    }
    i++;
}


应该做到的。

关于c++ - 用while循环替换for循环时,我在做什么错? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35142239/

10-09 06:24
查看更多