通过参考,在C++中得到错误答案

  • 本文关键字:错误 答案 C++ 参考 c++
  • 更新时间 :
  • 英文 :


当直接打印"所得税;它给出了预期的输出,但当变量的值更新时,它给出了错误的答案。它在在线编译器中运行良好。

这可能是什么原因?

//  Using Reference Variable
#include<iostream>
using namespace std;
void incomeAfterTax(int &income)
{
float tax = 0.10;
cout << income-income*tax << endl;          // printing 90
income = income - income*tax;
cout << income << endl;                     // but here it is 89
}
int main()
{
int salary = 100;
cout << "Total Salary: " << salary << endl;
incomeAfterTax(salary);
cout << "Income After Tax: " << salary;      // prints 89 
return 0;
}

这可能是一个浮点问题;如果"所得税"的结果被转换为整数。

这个问题可以通过在(对于C++11(中使用round((函数来避免。(roundf((如果使用C99(

#include<iostream>
#include <cstdint>
#include<cmath>
using namespace std;
void incomeAfterTax(int& income)
{
const float tax = 0.10;
cout << income-income*tax << endl;          
const float tax_amt = static_cast<float>(income) * tax; // income is int, cast to float
income -= round(tax_amt);  //round the float value to closest int
cout << income << endl;                     
}
int main()
{
int salary = 100;
cout << "Total Salary: " << salary << endl;
incomeAfterTax(salary);
cout << "Income After Tax: " << salary;      
return 0;
}

最新更新