-1

I am trying to write a C program to input number of coins for 25 paise, 50 paise, 1 rupee and 2 rupees and calculate total amount in rupees. This is my code. I am not getting the correct result.

For example for 5 coins of 25 paise, I should get Rs 1.25. But I am getting Rs 1.00. I am very new to C. Please indicate my mistake

#include <stdio.h>

//Q 7d 2011 7th paper Honours 2008 syllabus
int main()

{
int paise25, paise50, rs1, rs2;
double total;
printf("\n Number of coins of:\n\n");
printf(" 25 paise    = ");
scanf("%d",&paise25);
printf(" 50 paise   = ");
scanf("%d",&paise50);
printf(" 1 rupee = ");
scanf("%d",&rs1);
printf(" 2 rupee      = ");
scanf("%d",&rs2);

total=paise25/4 + paise50/2 + rs1 + 2*rs2;
//if(stat<40 || chemistry<40 || physics<40 || math<40 || c<40)

printf("\n Total amount in rupees: Rs %.02f\n",total);

return 0;
}
Asim Das
  • 93
  • 4
  • 11

2 Answers2

4

The problem is in this line:

total=paise25/4 + paise50/2 + rs1 + 2*rs2;

When you divide an integer by another integer - you get an integer. If you want to get a floating point value - you should make this intention explicitly. For example:

total=paise25/4.0 + paise50/2.0 + rs1 + 2*rs2;

Note the .0 parts that I've added - they will make the difference.

Kalin Varbanov
  • 363
  • 3
  • 13
  • 1
    Appending a `.` would be sufficient, no need for the additional `0`. – alk Mar 06 '16 at 11:23
  • 1
    True, but in my opinion it could be a bit confusing for newbies. If you compare 4. to 4.0 through the eyes of a newbie - it might not be obvious from the first time that they are the same. I really doubt that there is someone out there who doesn't know from Math classes from school that 4.0 is the same as the number 4. – Kalin Varbanov Mar 06 '16 at 11:26
3

When you divide 2 integers, the decimal point is truncated.

E.g 5/4 = 1 for integers.

Thus:

total = ((double)paise25)/4 + ((double)paise50)/2 + rs1 + 2*rs2;
Lincoln Cheng
  • 2,263
  • 1
  • 11
  • 17