简体   繁体   中英

Not taking the input

I want to write a program that only takes odd numbers, and if you input 0 it will output the addition and average, without taking any even number values to the average and the addition. I'm stuck with not letting it take the even values.. Heres my code so far:

    int num = 0;
    int addition = 0;
    int numberOfInputs = 0;

    cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;

    for (; ;) {

    cin >> num;
    numberOfInputs++;
    addition = addition + num;

    if (num % 2 != 0) {
     //my issue is with this part
        cout << "ignored" << endl;
    }

    if (num == 0) {
        cout << "Addition: " << addition << endl;
        cout << "Average: " << addition / numberOfInputs << endl;
        }
} 

Solution of your code:

Your code doesn't working because of following reasons:

Issue 1: You adding inputs number without checking whether it's even or not

Issue 2: If would like skip even then your condition should be as follow inside of the loop:

if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
} 

Solving your issues, I have update your program as following :

#include <iostream>
#include <string>
using namespace std;

int main()
{
  int num = 0;
int addition = 0;
int numberOfInputs = 0;

cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;

for (; ;) {

cin>> num;

 if (num%2==0) {
    cout << "ignored:" <<num << endl;
    continue;
}
numberOfInputs++;
addition = addition + num;



if (num == 0) {
    cout << "Addition: " << addition << endl;
    cout << "Average: " << addition / numberOfInputs << endl;
    break;
    }
 } 

}
#include <iostream>
#include <stdio.h>
using namespace std;

int main() {
    int number;
    int sum=0;
    int average=0;
    int inputArray[20]; // will take only 20 inputs at a time
    int i,index = 0;
    int size;

    do{
    cout<<"Enter number\n";
    cin>>number;

    if(number==0){

        for(i=0;i<index;i++){
            sum = sum + inputArray[i];
        }

        cout << sum;
        average = sum / index;
        cout << average;

    } else if(number % 2 != 0){
               inputArray[index++] = number;
    } else 
    cout<<"skip";

    }
    while(number!=0);
    return 0;
}

You can run and check this code here https://www.codechef.com/ide by providing custom input

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