【问题标题】:why is my code not accepting letters as user input为什么我的代码不接受字母作为用户输入
【发布时间】:2021-12-25 08:17:10
【问题描述】:

我的代码运行时没有错误或任何东西,但在我输入“F”或“P”后,它会跳到“单击任何按钮继续”,但如果我使用任何数字,它会通过代码正常运行。

这是我的代码:

#include <iostream>
#include <iomanip> // needed to use set precision

using namespace std;

void calcCost(double f_benefits, double F, double total_cost, double emp_salary)
{
    if (f_benefits == F)
        (total_cost += emp_salary * 1.5);
    else 
        (total_cost += emp_salary * 1.25);   // calculating operating function

}

int main()
{
    
    double num_emp = 0; // employees
    double emp_salary = 0; // employees salary
    double f_benefits = 0; // are they full time or part time benifits
    double total_cost = 0;
    int F = 0;
    int P = 0;

    cout << setw(69) << "Cost of Operation\n\n";

    cout << "Please enter the number of employees to process: ";
    cin >> num_emp;
    cout << endl;

    for (int i = 1; i <= num_emp; i++)  // loop for each employees salary and benifits
    {
        cout << "Please enter the salary for employee " << i << ":";
        cin >> emp_salary;
            
        cout << "Is employee " << i << " receiving(F)ull or (P)artial benefits ? Please enter F or P : "; // Dont forget input validation for this step
        cin >> f_benefits;
        
    }

        return 0;
}

【问题讨论】:

  • double num_emp = 0; // employees -- 为什么员工人数是浮点数?您预计有 1.4523 名员工,还是 0.75 名员工?

标签: c++ loops for-loop


【解决方案1】:

f_benefits 不应该是字符串吗?

【讨论】:

  • 我是新手,所以请原谅我,但是当我将它作为字符串尝试时,它不起作用,甚至不允许我访问我的代码。所以我不得不把它改回双
【解决方案2】:

“cin >> f_benefits”正在尝试读取双精度值。您应该将响应读入字符或字符串。读入字符串需要在返回之前换行。

你还应该检查你得到的是“F”还是“P”。

【讨论】:

  • 谢谢你,我意识到我的“F”和“P”是错误的数据类型。
猜你喜欢
  • 1970-01-01
  • 2017-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 2020-09-26
相关资源
最近更新 更多