Maitreyi Paweria
Maitreyi Paweria

Reputation: 1

Pass By Reference, Getting Incorrect Answer in C++

This is a simple Pass By Reference Problem to calculate the salary after tax, when directly printing "income-income*tax" it's giving the expected output but when the value of variable is updated it's giving a wrong answer. It is working fine in the online compiler.

What could be the reason of this?

//  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;
}

Upvotes: 0

Views: 101

Answers (1)

thelizardking34
thelizardking34

Reputation: 348

This is probably a floating point issue; were the result of 'income-tax' is being converted to an integer.

The issue is avoidable by using the round() function in (for C++11). (roundf() if using 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;
}

Upvotes: 1

Related Questions