[英]I have a (logical?) error on my loop with an array
Okay so bear with me if my title was very vague. 好吧,如果我的头衔很模糊,请多多包涵。 I even tried googling my problem and searching it here but I really can't think of a sentence that would best describe my problem. 我什至尝试谷歌搜索我的问题并在此处搜索,但我真的想不出最能描述我问题的句子。
I have an assignment and it goes like this: 我有一个作业,它像这样:
Write a program that reads a set of integers and then finds and prints the sum of the even and odd integers 编写一个程序,该程序读取一组整数,然后查找并打印偶数和奇数整数的和
I thought of the solution already and determined to use an array to store the numbers that the user will input and using an if/else statement to add the even and odd numbers together. 我已经想到了解决方案,因此决定使用数组存储用户将输入的数字,并使用if / else语句将偶数和奇数加在一起。 So far my code below words for even numbers but I really can't find the reason why whenever I try to add the odd numbers it ends up with a really large number. 到目前为止,我的代码下面的单词都是偶数,但是我真的找不到为什么每次尝试添加奇数时它都会得到一个很大的数字的原因。
Ex: I enter 13 and 17, I'll get 4253907, this does not affect the even numbers whatsoever even if I place the odd and even numbers in specific indices of the array. 例如:我输入13和17,我将得到4253907,即使我将奇数和偶数放在数组的特定索引中,这也不会影响偶数。 The even numbers will add properly but the odd numbers won't. 偶数将正确添加,而奇数则不会。
Here's what I've got so far 这是到目前为止我得到的
int length, evenSum, oddSum, temp, arsize;
cout <<"Input how many integers will be evaluated: ";
cin >> length;
arsize = length-1;
int num[arsize];
for(int i = 0; i<=arsize; i++)
{
cout<<"Input integer " << i+1 <<": ";
cin>>num[i];
}
for(int i = 0; i<=arsize; i++)
{
if(num[i]%2 != 0)
{
oddSum += num[i];
}
else
evenSum += num[i];
}
cout << "Sum of even integers: " << evenSum << endl;
cout << "Sum of odd integers: " << oddSum;
This should help : 这应该有帮助:
int evenSum = 0, oddSum = 0;
initialise the variables. 初始化变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.