C ++类。类内的值不会更新

时间:2013-10-13 01:26:40

标签: c++ class

对于类赋值我必须编写一个类定义。它叫做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 个答案:

答案 0 :(得分:1)

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

此行,如果percent小于99,percent/100将为零,这就是为什么它对您的结果没有影响。您可能希望double使用emplSalary and percent类型。

答案 1 :(得分:1)

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

您正在那里执行整数运算(emplSalaraypercent都是int类型)。这意味着percent / 100将(除非百分比大于99)总是评估为0.因此等式最终为emplSalary = emplSalary * 1

答案 2 :(得分:1)

问题出在这一行:

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

因为percentint,所以你正在进行所有整数数学运算。

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

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

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

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

答案 3 :(得分:0)

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

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