[英]How to Fix Blank Results when use for loop in c++
我是 Alvin,我是 C++ 編程語言的初學者,我有一個代碼:
#include <iostream>
#include <string>
using namespace std;
int main(){
for (int i=0; i == 5; i++){
cout << i << ", ";
}
system("pause"); // i add this code to avoid program close when i try to run it
return 0;
}
當我編譯它不顯示錯誤消息即成功編譯但是,當我嘗試運行它時,它不顯示'i'值,即它顯示空白屏幕。 有人可以幫助我嗎?
您似乎不理解 C for-loop 中條目的含義:
for (int i=0; i==5; i++)
方法:
Start with i being zero (i=0)
Continue the loop, AS LONG AS i equals 5 (i==5)
換句話說,這並不意味着:
...
Continue the loop, UNTIL i equals 5
因此,您需要將i==5
替換為i<=5
,因為這意味着:
...
Continue the loop, AS LONG AS i is smaller or equal than 5 (i<=5)
您在循環測試條件中有一個邏輯錯誤:
for (int i=0; i == 5; i++){ // the `==` will cause it to never enter the loop
應該:
for (int i=0; i <= 5; i++){
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.