简体   繁体   English

为什么arrays用的是i++

[英]Why is the i++ used in arrays

#include <iostream>

int main()
{
    int myArray[5];     // array of 5 integers lol
    int i;
    for (i=0; i<5; i++ )  // 0 - 4
    {
        std::cout << "Value for myArray[" << i << " ]: ";
        std::cin >> myArray[i];
    }
    for (i = 0; i<5; i++)
    std::cout << i << ": " << myArray[i] << std::endl;
    return 0;
}

Why is i++ required for this program to work?为什么这个程序需要 i++ 才能运行?

Because if you don't execute i++ (or any other statement which increments i ), i will remain 0 , the condition i < 5 will always remain true and the loop will never end.因为如果您不执行i++ (或任何其他增加i的语句), i将保持0 ,条件i < 5将始终保持为真,并且循环将永远不会结束。

The ++ is the increment operator, and increments the value of i in each iteration of the loop. ++ 是递增运算符,在循环的每次迭代中递增 i 的值。

i++ is just a short hand for i++ 只是简写

i = i + 1;

If you don't increment your loop counter then the loop will never end for example this would be an infinite loop如果您不增加循环计数器,那么循环将永远不会结束,例如这将是一个无限循环

for(i = 0; i < 5; i+ 1)
  /*do something*/

i++ increases the i variable.. you can also use i-- in the loop to decrease the i variable. i++ 增加 i 变量。您也可以在循环中使用 i-- 来减少 i 变量。

Or even i+=2 to increment the variable by two.甚至 i+=2 将变量增加 2。

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

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