是否有一种方法可以在输入负数时平均不包括负数,这是您终止程序的方式
Is there a way to not include a negative number in an average, when entering a negative number is how you terminate the program?
很抱歉上次看到我以前的线程的人。它充满了粗心的错误和错别字。这是我的作业:
"编写一个程序,该程序将使用户能够通过输入语句输入一系列非阴性数字。在输入过程结束时,该程序将显示:奇数数及其平均值;数字;均匀的数字及其平均值;输入的数量总数。启用输入过程以输入负值停止。确保建议用户该结束条件。"
这是我的代码:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number, total1=0, total2=0, count1=0, count2=0;
do
{
cout << "Please enter a number. The program will add up the odd and even ones separately, and average them: ";
cin >> number;
if(number % 2 == 0)
{
count1++;
total1+=number;
}
else if (number >= 0)
{
count2++;
total2+=number;
}
}
while (number>=0);
int avg1 = total1/count1;
int avg2 = total2/count2;
cout << "The average of your odd numbers are: " << avg1 << endl;
cout << "The average of your even numbers are " << avg2 << endl;
}
它似乎工作正常,但是当我输入一个负号以终止程序时,它将其与其他平均数字一起。有什么建议可以解决这个问题吗?我知道这是可能的,但是这个想法逃脱了。
您的主要循环应该是这样的:
#include <iostream>
for (int n; std::cout << "Enter a number: " && std::cin >> n && n >= 0; )
{
// process n
}
或,如果要发射诊断:
for (int n; ; )
{
std::cout << "Enter a number: ";
if (!(std::cin >> n)) { std::cout << "Goodbye!n"; break; }
if (n < 0) { std::cout << "Non-positve number!n"; break; }
// process n
}
之后:
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
立即检查数字是否为负
if(number < 0) break;
现在,您无需在检查数字是否为负时使用DO-while循环。因此,您可以使用无限循环:
while(true) {
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
if(number < 0) break;
// The rest of the code...
}
附加:您的代码有问题。您没有向用户显示偶数和奇数数量的数量,并输入了数字总数。
另一个附加:您应该使用更有意义的变量名称:
int totalNumEntered = 0, sumEven = 0, sumOdd = 0, numEven = 0, numOdd = 0;
当然,我不会将您限制为这些名称。您也可以使用其他类似名称。
对于整数部门问题:您必须将表达值投入到适当的类型(在这种情况下为float
)。您还应该将平均变量类型更改为 float
:
float avg1 = float(total1) / float(count1);
float avg2 = float(total2) / float(count2);
cin>>>>编号后,请检查&lt;0,如果是这样,请打破。尝试逐行逐步浏览程序,以感觉到执行流程。学习有趣的学习,祝你好运!
相关文章:
- 为什么 cmake 许可证<>样式不包括?
- 计算平均值,不包括上次得分
- 将值从另一个数组写入数组,不包括不需要的值 C++
- 如果语句不包括文本行?
- 找到 x^n 的所有组合,并检查它们的总和是否等于一个不包括相同数字的数字
- 如何保证不包括 iostream?
- 创建一个循环,该循环将输出大于零且小于 60(不包括 60)的所有 5 的倍数
- C/C++ 经过的流程周期,不包括断点处
- 回文,不包括特殊字符和空格
- 查找 n 个数字的公因数数(不包括"1"作为公因数)
- 在 C++ 中的 SetClipboardData() 之后粘贴不包括记事本的换行符
- C++11 exit() 和 abs() 不包括 <cstdlib>?
- 生成生成 makefile 时不包括 cmake C++11 标志
- 寻找一种单一的定时方法来测试各种算法,不包括它们的输入
- 提升正则表达式 cpp 用于查找 %% 之间的字符串,输出不包括 % 字符本身
- gSoap 不包括信封和正文开始标签
- 与不包括一个标头更好的使用不完整的标头比另一个标头的使用无效
- 在不包括任何内容的情况下获得错误声音
- 运行单元测试不包括Catch2中的特定标签
- 是否有一种方法可以在输入负数时平均不包括负数,这是您终止程序的方式