Wrong output using int for finding simple interest

I made a simple program to find out simple interest. But when I use int(integer) for variable deceleration it shows wrong output. Whereas using double and float it is showing correct.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
void main()
{
 clrscr();
 int i,p,r,t;
 cout<<"Enter Principal ";
 cin>>p;
 cout<<"Enter Interest rate ";
 cin>>r;
 cout<<"Enter time ";
 cin>>t;
 i=p*r*t/100;
 cout<<"Interest= "<<i;
 getch();
}


NOTE: I code in TurboC++ which need clrscr(); and getch(); to get correct output. So, I'm sure they are not causing any problems.
Last edited on
That's because dividing an int by an int will alway produce an int as an output unless you cast it to a float. I would suggestcout<<"Interest= "<<(float)(p*r*t/100);. Or just declare i as a float. You don't actually specify as to why you need to use ints, is there a reason?
No its my habit to use ints for programs like this.
Anyway you said "dividing an int by an int will always produce an int" but when I take
principal = 3000
interest rate = 5
time = 4
It gives output -55. How's it possible??

And when I use float instead of int it gives 600, which is correct. Also note that 600 is also an integer.
Last edited on
No its my habit to use ints for programs like this.

Well, that's wrong in this instance.

If t is 4, what do you think t/100 (line 11) produces?
Hint: 0. p*r*0 will always be 0.
Not sure where you're getting the -55.

If t is 4, what do you think t/100 (line 11) produces?

Multiplication and division have the same precedence level and both associate left-to-right. So, all the multiplication on that line is done before the division.


Not sure where you're getting the -55.

I am. He's in an environment where the native size of int is 16 bit and he's running into overflow. 3000 * 5 * 4 is a greater value than a 16 bit signed int can hold.

http://ideone.com/7L40Kn

If at all possible, I would recommend the OP upgrade to a modern C++ compiler.
Last edited on
Alright, thanks helping. :)
Topic archived. No new replies allowed.