简体   繁体   English

不接受输入

[英]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. 我想编写一个只接受奇数的程序,如果输入0,它将输出加法和平均值,而对平均值和加法不取任何偶数值。 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 问题1:您添加输入数字而不检查它是否是偶数

Issue 2: If would like skip even then your condition should be as follow inside of the loop: 问题2:如果想甚至跳过,则循环中的条件应如下:

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 您可以在https://www.codechef.com/ide上运行并检查此代码,方法是提供自定义输入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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