我的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");
}
最佳答案
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;
}
关于c++ - 每次迭代后添加for循环的结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22432240/