简体   繁体   中英

Total number of odd/even numbers

Hello I'm trying to display only the amount of odd/even numbers for the digits entered. I've tried multiple methods but failed to find any solution. This is the problem and what I have so far.

Write a program that allows the user to enter 10 separate whole numbers. After accepting these 10 numbers from the user, the program should display output to the user informing them how many of the numbers entered were odd numbers and how many were even numbers.

#include <iostream>
using namespace std;

int main() {
    char even, odd;
    int number;

    for(int i = 1;i<=10;i++) { 
        cout << "Enter Number " << i << ":" ;
        i=i+0;
        cin >> number ;

    }
    if (number%2==0){
        number = even;
    }
    cout<< "You entered:\n";
    cout << "Odd Numbers: " << odd << endl;
    cout << "Even Numbers: " << even << endl;
    return 0;
}

There are a few things in your code that do not look right.

for(int i = 1; i <= 10; i++)
{
    cout << "Enter Number " << i << ":";
    i = i + 0;
    cin >> number;
}

What are you hoping to accomplish with the line i = i + 0 ? Your loop will work just fine without it.

char even, odd;

Technically, since char is a numeric type, you may keep track of the number of even and odd numbers encountered by keeping track of them. However, you aren't doing that.

The statement:

if (number%2==0){
    number = even;
}

Is saying that if the input number is even, assign the current value of char even to number . However, this doesn't make sense, since you never stored a value in even earlier. Also, you're doing this outside the loop, so effectively only the last of the 10 values read into number would ever be counted in your calculations (if you had that done correctly).

What you should do:

int even = 0, odd = 0;

for(...)
{
     // read input into "number"...
     if(number % 2 == 0)
     {
         even++;
     }
     else
     {
         odd++;
     }
}

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