gpt4 book ai didi

c++ - 不接受输入

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:45:04 27 4
gpt4 key购买 nike

我想写一个只取奇数的程序,如果你输入0它会输出加法和平均值,而不取任何偶数值来求平均值和加法。我坚持不让它采用偶数..到目前为止,这是我的代码:

    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;
}
}

最佳答案

您的代码的解决方案:

由于以下原因,您的代码无法正常工作:

问题 1:您添加输入数字而不检查它是否为偶数

问题 2:如果想跳过,那么您的条件在循环内应该如下所示:

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

为了解决您的问题,我已将您的程序更新如下:

#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;
}
}

}

关于c++ - 不接受输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40439745/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com