在每次迭代后添加for循环的结果

时间:2014-03-16 02:22:19

标签: c++ for-loop

我的for循环遇到了麻烦。我有一个基本的2次表,从1到10上升(见下文)。我正在尝试添加结果,以便在每次循环后,allResult显示添加的所有结果的值。它需要显示每个循环后添加的所有结果。而且我不知道如何去做。更好的描述是代码中评论的期望结果。

我的代码......

int main(){

int allResult;

for( int i = 1; i < 11; i++)
{

    int result = 2*i;

    cout << 2 << " times " << i << " = " <<  result << endl;

    // I want allResult to store results added. so after first loop, result = 2 so allResult = 2
    // after second loop, result = 4. so allResult should be 6. (results from 1 and 2 added)
    // after third loop, result = 6 so allResult should be 12. (results from 1, 2 and 3 added)
    // I'm trying to apply this to something else, that uses random numbers, so i cant just * result by 2.


}
system("pause");
}

3 个答案:

答案 0 :(得分:3)

int allResult = 0;
for( int i = 1; i < 11; i++)
{
     allResult += 2*i;  
    cout << 2 << " times " << i << " = " <<  2*i << endl;

}

答案 1 :(得分:2)

int allResult = 0;
for( int i = 1; i < 11; i++)
{
    int result = 2*i;

    cout << "2 times " << i << " = " <<  result << endl;
    allResult += result;
    cout << "allResult: " << allResult << endl;
}

答案 2 :(得分:1)

int main()
{

int allResult=0;

 for( int i = 1; i < 11; i++)
  {

      int result = 2*i;

      allResult=allResult+result; 
/*Initially allResult is 0. After each loop iteration it adds to its previous 
value. For instance in the first loop it was allResult=0+2, 
which made allResult equal to 2. In the next loop allResult=2+4=6. 
Third Loop: allResult=6+6=12. Fourth loop:allResult 12+8=20 and so on..*/

cout << 2 << " times " << i << " = " <<  result << endl;
  }

      system("pause");
}