0

对于班级作业,我必须编写班级定义。它被称为 Employee 类,对于我的第一个 c++ 类来说是非常基础的东西。

我的问题出在第一个 forloop 中,当我尝试根据新百分比调整薪水时。之后类中的变量不会改变。我不知道有什么问题了。

代码是:

#include <iostream>
#include <string>

using namespace std;


class Employee
{
private:
    int emplSalary;
    string employeeName;

public:
    Employee();
    Employee(string name,int salary);
    string getName();
    int getSalary();
    void newSalary(int percent); 
    void input();
    void output();
};
Employee::Employee()
{
    emplSalary=0;
    employeeName="";
}
Employee::Employee(string name,int sal)
{
    employeeName=name;
    emplSalary =sal;
}
string Employee::getName()
{
    return employeeName;
}
int Employee::getSalary()
{
    return emplSalary;
}
void Employee::newSalary(int percent)
{

    emplSalary= emplSalary *(1+(percent/100));
    cout<<"I calculated"<<endl;
    /*
    if(percent < 0) 
    {
        cout<<"Invalid Percentage";
        cout<<"I calculated"<<endl;
    }
    else
    {
        emplSalary= emplSalary *(1+(percent/100));
        cout<<"I calculated"<<endl;
    }
    */
}
void Employee::input()
{
    cout << "Enter Name: "; 
        cin>> employeeName;
        cout<<"\n";
        cout<<"Enter Salary: " ;
        cin>>emplSalary;
        cout<<"\n";
}
void Employee::output()
{
    cout << "Name: " << employeeName <<" : "<< "Salary: " << emplSalary << endl;
    cout<<"\n";
}


int main()
{
    const int NUMBER_EMPLOYEE =1;
    Employee employees[NUMBER_EMPLOYEE];
    int percent;
    cout<<"Welcome to Employee program. Enter Name and Salary when prompted."<<endl;
    cout<<"\n";
    cout<<"\n";


    for (int i=0; i<NUMBER_EMPLOYEE; i++)
    {

        employees[i]=Employee();
        employees[i].input();
        cout<<"What percentage to raise the salary: ";
        cin>>percent;
        employees[i].newSalary(percent);
    }
    for (int i=0; i<NUMBER_EMPLOYEE; i++)
    {
        employees[i].output();
    }


    return EXIT_SUCCESS;
}

输出是:

Welcome to Employee program. Enter Name and Salary when prompted.


Enter Name: 
Enter Salary: 
What percentage to raise the salary: I calculated
Name:  : Salary: 0
4

4 回答 4

1
emplSalary= emplSalary *(1+(percent/100));

这条线,如果你percent小于 99,percent/100将是零,这就是它对你的结果没有影响的原因。您可能想double为您的emplSalary and percent.

于 2013-10-13T01:34:16.400 回答
1
emplSalary= emplSalary *(1+(percent/100));

您正在那里执行整数算术(emplSalaray并且percent都是 type int)。这意味着percent / 100将(除非百分比大于 99)始终计算为 0。因此等式最终为emplSalary = emplSalary * 1

于 2013-10-13T01:35:14.717 回答
1

问题出在这一行:

emplSalary= emplSalary *(1+(percent/100));

因为percentint,所以你正在做所有的整数数学。

假设percent是 50。表达式的最里面部分最终是50/100,它是0整数数学。(您希望结果是0.50)。

要解决此问题,请将百分比的类型更改为double

或者,您可以将 100 更改为 100.0 (使其成为 a double):

emplSalary= emplSalary *(1+(percent/100.0));
于 2013-10-13T01:35:28.170 回答
0

首先,请注意,当原始薪水为零时(当您编写employees[i]=Employee()默认构造函数将薪水设置为 0 时会发生这种情况),任何百分比的加薪将始终保持为零,

其次,请注意,将一个int除以另一个int将执行整数运算,因此商会被截断。因此,0% 到 100% 之间的加幅将四舍五入为 0%。除以 100.0 而不是 100 以解决该问题。

于 2013-10-13T01:36:54.530 回答