【发布时间】:2014-11-06 20:32:42
【问题描述】:
所以我编写了一个函数,该函数应该计算用户选择 N 的数组中的所有前 N 个偶数。这很好,但是如果数组中的偶数少于 N,则该函数应该只需将它们全部添加,这是我遇到困难的部分。
函数调用:
cout << "The sum of the first " << userSum << " even numbers is: " <<
SumEvens(list, SIZE, userSum) << endl;
函数定义:
int SumEvens(int arr[], const int size, int evensAdd)
{
int sum = 0;
for (int i = 0; i < size; i++){
if (arr[i] % 2 == 0 && arr[i] != 0){//if the number is even and not 0 then that number is added to the sum
evensAdd--;
sum += arr[i];
}
if(evensAdd == 0)//once evensAdd = 0(N as previously mentioned) then the function will return the sum
return sum;
}
}
例如,如果我有一个数组:{1,2,3,4,5}
并要求它计算前 2 个偶数之和,它将输出 6
但是,如果我要求它计算前 3 个或 4 个或 5 个偶数,它将输出总和为 6
为什么要减一?
【问题讨论】:
-
我建议使用
std::vector<int>来获取结果。 -
请考虑接受对您有帮助的答案,以便其他用户立即看到为您解决问题的方法。
标签: c++ function for-loop controls call