解决
谢谢保罗,我的问题最终变得非常简单,我只是让它不必要地复杂化,这只是进一步推动了这个问题。问题最终是我在函数的if否定语句中添加了一个不必要的cin,导致它在计算中的某处添加了负数。
我将在原始帖子中保留相同的代码现在只是因为其他人需要协助处理这种性质的问题。
好吧,所以我对这段代码感到有些困惑。它旨在计算公司员工错过的平均天数。
删除了评论,但问题是,当遇到负数时,仍然会通过仍然等于负数的天数减去总数(daysM)。
我试图通过使用daysforneg变量来解决这个问题,直到输入一个正整数来解释任何负数,但它会导致相同的问题
我的问题是我如何在numMissed函数中获得一个循环以及do-while循环,以便在没有问题持续存在的情况下禁止负数?任何帮助将不胜感激。
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
/* prototypes */
int numEmp();
int numMissed(int);
double avgDays(int, int);
/////////////////////
/* Full functions */
int numEmp()
{
int employees;
cout<<"How many employees are in the company? ";
cin>>employees;
while(employees<1)
{
cout<<"Invalid answer. Try again: ";
cin>>employees;
}
return employees;
}
////////////////////////////////////////////////////////////////////////////////
int numMissed(int employees)
{
int daysforneg; ///negative numbers
int daysM=0,days; ///Days is days missed per employee
int x=0;
do
{
cout<<"How many days were missed by these employees in the past year? ";
cin>>days;
if(days>=0)
{
daysM+=days; //Calcs total days missed throughout
x++;
}
else if(days<0)
{
cout<<"No negative numbers, sorry. Try again: ";
cin>>daysforneg;
if(daysforneg>0)
{
x++;
days=daysforneg;
}
else
{
!(x++);
}
}
}
while(x<employees);
return daysM;
}
/////////////////////////////////////////////////////////////////////////////////
double avgDays(int daysM, int employees)
{
double avg;
avg=(daysM*1.0)/employees;
return avg;
}
int main()
{
int employees, daysM;
double avg;
employees=numEmp();
daysM=numMissed(employees);
avg=avgDays(daysM, employees);
cout<<avg;
return 0;
}
答案 0 :(得分:0)
如果目标只是“再试一次”,如果输入为负数,则可以使用while
简单地完成循环:
int numMissed(int employees)
{
int daysforneg; ///negative numbers
int daysM=0,days; ///Days is days missed per employee
int x=0;
while (x < employees )
{
cout<<"How many days were missed by these employees in the past year? ";
cin>>days;
if(days>=0)
{
daysM += days;
x++;
}
else
{
cout<<"No negative numbers, sorry. Try again: ";
continue;
}
}
return daysM;
}
输入的天数为负数的条件,所有需要做的就是返回到循环的顶部而不增加计数器x
。