简体   繁体   中英

total the even numbers and product the odd

I am trying to make code that gets from user, the number of inputs and value of each input and then calculate total sum of the even numbers and product of the odd numbers.

I get to put in the first number but then the for loop does not work.

#include <iostream>
#include <vector>

int main() {

int totalNum;
int total_even;
int product_odd;
std::vector<int> numbers;

std::cout << "How many numbers would you like to entre?:";
std::cin >> totalNum;
std::cout << "\n";

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

std::cout << "Please entre number " << i << "\n";
std::cin >> numbers[i];

if (numbers[i] % 2 == 0) {

  total_even = total_even + numbers[i];

} else {

  product_odd = product_odd * numbers[i];
}

}
std::cout << "Sum of even: " << total_even << "\n";
std::cout << "Product of odd: " << product_odd;
}

First off, there's no need for a vector since, once you've finished with the number, you never need to use it again. Getting rid of the vector will remove the erroneous assignment to a non-existing element (appending to a vector is done with push_back rather than assigning beyond the end).

Second, since you're either adding the number to, or multiplying the number by, some accumulator, the accumulators should be initialised. You should initiliase total_even to zero and product_odd to one, so that the operations work out ( 0 + a + b == a + b , 1 * a * b == a * b ). As it stands at the moment, your initial values are arbitrary so your results will also be arbitrary.


By way of example, here's a possible solution (though you should edit your own program rather than use this verbatim: it's a near-certainty that educators will be checking classwork, assuming that's what this is, for plagiarism):

#include <iostream>

int main() {
    int numCount, thisNum, sumEven = 0, productOdd = 1;

    std::cout << "How many numbers would you like to enter? ";
    std::cin >> numCount;
    std::cout << "\n";

    for (int i = 1; i <= numCount; i++) {
        std::cout << "Please enter number #" << i << ": ";
        std::cin >> thisNum;
        if (thisNum % 2 == 0) {
            sumEven += thisNum;
        } else {
            productOdd *= thisNum;
        }
    }

    std::cout << "\nSum of even: " << sumEven << "\n";
    std::cout << "Product of odd: " << productOdd << "\n";
}

A sample run:

How many numbers would you like to enter? 6

Please enter number #1: 1
Please enter number #2: 2
Please enter number #3: 3
Please enter number #4: 4
Please enter number #5: 5
Please enter number #6: 6

Sum of even: 12
Product of odd: 15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM