0

当我输入员工人数的小数时,它会无限次输出“请输入至少 1 的值”。但是小数点不应该被截断吗?我该如何解决这个问题,以便删除小数点。这也发生在 daysMissed 的输入中。

#include <iomanip> 
#include <iostream>

using namespace std;

int getNumEmployees();
int getDaysMissed(int);
double getAverageDays(int,int);

int main()
{
int numEmployees;
int daysMissed;
double average;

    //Get the number of employees
numEmployees = getNumEmployees();

//Get the number of days missed
daysMissed = getDaysMissed(numEmployees);

//Get the average days missed
average = getAverageDays(numEmployees, daysMissed);

cout << "The average number of days missed is: " << average << endl;

system("pause");
return 0;
}

int getNumEmployees()
{
    int employeeNum;

    cout << "Enter the number of company employees: ";
    cin >> employeeNum;

    while(employeeNum < 1)
        {
            cout << "Please enter a value of atleast 1 " << endl;
            cin >> employeeNum;
        }

    return employeeNum;
}


int getDaysMissed(int employeeNum)
{
int totalDays = 0;
int employee;

for(int count = 1; count <= employeeNum; count++)
{
    cout << "Enter the number of days employee " << count << " missed: ";
    cin >> employee;
    while(employee < 0)
        {
        cout << "Enter a positive number for days missed " <<     endl;
            cin >> employee;
        }

    totalDays += employee;
}
return totalDays;
 }

double getAverageDays(int employeeNum, int totalDays)
{
double averageDays;

averageDays = totalDays / employeeNum;

return averageDays;

}
4

2 回答 2

2
int employeeNum;
cin >> employeeNum;

此代码尝试解析intfrom std::cin。首先,您实际上并没有在之后检查流状态 - 您假设employeeNum < 1充分传达了失败,但这通常不是最好的方法:输入流上可能存在 EOF 或错误条件。对于前者,您的程序可能需要终止,对于后者,您可能希望忽略该输入行的其余部分并在重试之前清除错误条件:

#include <limits>

if (std::cin >> employeeNum)
    break; // no need to retry input...
else if (std::cin.eof())
    throw std::runtime_error("EOF on input");
else
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n').clear();

但是小数点不应该被截断吗?我该如何解决这个问题,以便删除小数点。

如果你想输入一个实数然后使用它的“截断”值,你需要输入一个doublefloat然后将它转换成一个int代码。假设您不需要范围检查...

double x;
if (std::cin >> x)
{
    int x_int = x;
    ...use x_int...
}
于 2013-03-26T02:08:54.347 回答
2

每次不成功cin的操作后,您需要使用:

cin.clear();

重置失败标志。
然后使用:

cin.ignore();

忽略刚刚导致错误的字符串,这样您就不会尝试再次解析它。

您应该执行以下操作:

int employeeNum = 0;
cout << "Enter the number of company employees: ";

while (!(cin >> employeeNum) || employeeNum < 1)
{
    if(cin.fail()) 
    {
        cout << endl << "Please enter a valid value: ";
        cin.clear ();   // reset the "failure" flag
    } 
    else if(employeeNum < 1) 
    {
        cout << "Please enter a value of at least 1: ";
    }
    // ignore the bad charactors
    // needed here incase '0.XX was entered
    cin.ignore(10000, '\n');
}

如果您输入的值是小数,那么小数将被截断,而不是四舍五入。

默认ignore只跳过 1 个字符,但如果您希望得到一个长的无效字符串(如小十进制:0.23),您应该将其更改ignore为:

cin.ignore(10000, '\n') 

这将跳过最多 10000 个字符或直到下一个换行符。

于 2013-03-26T01:49:54.340 回答