与c++程序混淆

confused with c++ program?

本文关键字:程序 c++      更新时间:2023-10-16

我已经编译了下面的程序,我知道它的作用,它需要十个数字乘以它自己,然后在最后将它们的总和相加。

    #include <iostream>
    using namespace std;
    main()
    {
    int a[10];//1
    int sumOfSquares = 0 ;//2
    int i =0; //3`enter code here`
    cout << "Please enter the ten numbers one by one " << endl;//4
    for (i = 0 ; i < 10 ; i++)//5 dont get what this does,   
                              //  obviously its a for loop, 
                              //  but why does it increment i by one
    {
    cin >> a [i];//6 this means store the 10 numbers
                 //  in array a and refer to it by the variable i
    }
    for (i = 0 ; i < 10 ; i++) //7 again i dont get why this is here
    {
    sumOfSquares = sumOfSquares + a[i]*a[i];//8
    }
   cout << "The sum of squares is "<< sumOfSquares << endl; //9
   }

为什么它使i增加一个

数组索引从0N-1,其中N是数组中的元素数。i++i的值增加1(相当于i = i + 1;)。在for循环中递增i是用于访问阵列a的每个元素的构造(按顺序):

for (int i = 0; i < 10; i++)
{
    a[i] = 2; /* just example */
}

相当于:

a[0] = 2;
a[1] = 2;
...
a[9] = 2;

正如其他人所评论的那样,买一本C++书(请参阅这个SO问题以获取C++书的列表)。

#include <iostream>
using namespace std;
main()
{
    //declare space in memory for 10 numbers to be stored sequentially
    //this is like having ten variables, a1, a2, a3, a4 but rather than having
    //hardcoded names, you can say a[4] or rather i=4, a[i], to get variable a4.
    int a[10];  
    int sumOfSquares = 0 ;  //space for a number to be stored called sumOfSquares
    int i =0;               //space for a number to be stored called i
    cout << "Please enter the ten numbers one by one " << endl; //print msg to screen
    for (i = 0 ; i < 10 ; i++) //make i = 0; while i < 10 run this code! increase i by 1 each time
    {
        //a stores 10 numbers. put the number the user entered in space
        //a[0] the first time, a[1] the second time, a[2] the third time etc etc.
        cin >> a [i];
    }
    //run this code 10 times, with i=0 the first time, i=1 the second time,
    // i=3 the third time etc etc.
    for (i = 0 ; i < 10 ; i++)
    {
        //get the number at a[0] multiple it by the number at a[0]
        //add it to value already in sumOfSquares so this number goes up and up and up.
        //the second time through the loop get a[1] and multiply it by a[1].
        sumOfSquares = sumOfSquares + a[i]*a[i]; 
    }
    //print answer to screen
    cout << "The sum of squares is "<< sumOfSquares << endl; //9

}