简体   繁体   English

我的数组循环出现错误(逻辑错误)

[英]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.

相关问题 我的代码中有什么错误。 我尝试在课堂上使用数组但出现逻辑错误 - What the error in my code. I try to use array in class but getting logical error 我在C ++中的Trie程序出现逻辑错误 - My Trie program in C++ have logical error 需要一些帮助在我的while循环中发现逻辑错误 - Need some help finding a logical error in my while loop 我有一个错误与我的for循环,不能找出为什么,我有一个“预期声明”错误 - I am having an error with my for loop and can't figure out why, I have an “expected declaration” error 数组项逻辑错误的总和 - Summation of array items logical error 我的阵列有足够的堆栈空间,为什么这个循环失败? - I have enough stack space for my array, so why does this loop fail? 我有一个程序可以计算一组数字的最小公倍数? 但是我似乎在某个地方遇到了逻辑错误 - I have a program that calculates the least common multiple of a set of numbers? But I seem to run into a logical error somewhere 我使用链表在堆栈上出错。 无法打印数字循环。 (C ++) - I have an error on my stack using a linked list. Unable to print loop of numbers. (C++) 为什么这个程序有逻辑错误 - Why does This program have a logical error 我的代码中有错误,未声明的标识符 - I have an error in my code, undeclared identifier
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM