我是C ++的新手,这是家庭作业。我不明白发生了什么。当我运行这个时,一切正常,如果我输入60000当前工资和.05加薪,但如果我输入52000当前工资和.23加薪,那么追溯工资为5982.00而不是5980.00它与小数或其他东西有关吗?我真的不知道。提前谢谢。
// Variables
char fullName[30]; // The user's full name - INPUT
int currentAnnual; // The users's current annual salary - INPUT
float percentIncrease; // The percent increase due on the
// current annual salary - INPUT
// The retroactive pay
float retroactive;
// The new monthly salary based on the pay increase and the new salary
float monthlySalary;
// The new salary the user should receive based on their old salary
// and their pay increase
float newSalary;
for(int lcv = 1; lcv <= 3; lcv++)
{
// INPUT
cout << "What is your full name? ";
cin.getline(fullName, 30);
cout << "What is your current salary? ";
cin >> currentAnnual;
cout << "What is your pay increase (please input percentage in"
"decimal format)? ";
cin >> percentIncrease;
// PROCESSING
newSalary = (currentAnnual * percentIncrease) + currentAnnual;
monthlySalary = newSalary / 12;
retroactive = (monthlySalary - (currentAnnual / 12)) * 6;
// OUTPUT
cout << endl;
cout << fullName << "'s Salary Information\n";
cout << left << setw(15) << "New Salary" << setw(19) << "Monthly Salary"
<< "Retroactive Pay\n";
cout << setprecision(2);
cout << fixed;
cout << right << setw(10) << newSalary << setw(19) << monthlySalary
<< setw(20) << retroactive << endl << endl;
cout << "<Press enter to continue>";
cin.ignore(100, '\n');
cin.ignore(1000, '\n');
cout << endl;
}
答案 0 :(得分:2)
将currentAnnual / 12
更改为currentAnnual / 12.0
以强制执行浮点计算。否则,计算的那部分将四舍五入到下面最接近的整数。
答案 1 :(得分:2)
currentAnnual / 12
C中两个整数的除法是“整数除法”(它给出一个整数),我想你不想这样。一种解决方案是将其更改为currentAnnual / 12.0
。无论如何,了解这里发生的事情非常重要。
答案 2 :(得分:0)
您应该monthlySalary = newSalary / 12.0;
而不是monthlySalary = newSalary / 12;
,因此您必须指定要除以浮点数。否则结果将是整数。例如125./12 = 10
,但125./12. = 10.41(6)
。当然,你会得到错误的结果。
尝试向所有常量添加.0
或.
。
答案 3 :(得分:0)
浮点计算不如您预期的那么准确。尝试在上面的代码中用float
替换double
(double
是一个“双精度浮点数”;它可以存储比float
更多的值,并且更精确)。
此外,操作顺序有时很重要,因此您可能希望将retroactive
计算重新排序为
6 * monthlySalery - currentAnnual / 0.5;
并尝试其他组合以查看最佳效果。