-2

I am facing issue with result output with long int. Here Below is my Program, I am calculating tax with various methods 1) taking result output in int and long variable. I think all the four results in my code should be the same, but result output in tax3 variable is coming different (less by 1) than other three. please help me to understand the reason.

#include<iostream.h>
#include<conio.h>

int main()
{
    long salary;
    cout << "Enter Salary: " << endl;
    cin>>salary;
    float tax1, tax2;
    long tax3, tax4;
    tax1 = salary*0.15;
    tax2 = (salary*15)/100;
    tax3 = salary*0.15;
    tax4 = (salary*15)/100;
    cout << "tax1=" << tax1 << endl;
    cout << "tax2=" << tax2 << endl;
    cout << "tax3=" << tax3 << endl;
    cout << "tax4=" << tax4 << endl;
    getch();
    return(0);
}
O'Neil
  • 3,790
  • 4
  • 16
  • 30
Ishaan
  • 75
  • 9

1 Answers1

0

There are two major types of numbers which are known by the compiler - floating points and Integers. The floating points follows IEEE-754 floating point for representation for 32 bit(float) and 64 bit(double). In turbo C the int is only 16 bits. Also when you copy from float to int only integer part is copied. i.e. consider the following example :

     float a=9.8;
     int b=(int)a;

In above code when you print b it will give only 9. Also a piece of advice for you, if you want to learn c++ better then please switch from turbo c to gcc.

  • Hey Ravinder thanks for your response, But still i didn't find my answer. In above example I am not doing any type conversion. Even a simple input of 100, don't you think result should be same. Unable to understand the different result at third output i.e "tax3" – Ishaan Jun 21 '18 at 17:12
  • @Ishaan while calculating tax3 you are multiplying with 0.15 its floating point. Please see google for type conversion while doing any operation. You can also refer to Dennis rechie c language. Its preety good explained there. And yes c and c++ have implementation for type conversion. – Ravinder Singh Jun 22 '18 at 01:05