If I just change the data type float to double in the following program, the code works fine for input 14.2 (and all inputs). However, if I use float instead of double, the program behaves strangely that, it works fine for all inputs EXCEPT 14.2!
#include <stdio.h>
#include <ctype.h>
void totalPrice(char, float);
int main()
{
char gasStation;
float tankSize;
printf("Enter the gas station: \n");
scanf("%c", &gasStation);
gasStation = toupper(gasStation);
printf("Enter the size of the gas tank: \n");
scanf("%f", &tankSize);
totalPrice(gasStation, tankSize);
}
void totalPrice(char gasStation, float tankSize)
{
float amount;
switch(gasStation)
{
case 'I':
if (tankSize == 5)
amount = (5*75.49) + (0.09*(5*75.49)) + (0.09*(5*75.49));
else if (tankSize == 14)
amount = (14.2*75.49) + (0.09*(14.2*75.49)) + (0.09*(14.2*75.49));
else if (tankSize == 19)
amount = (19*95.50) + (0.12*(19*95.50)) + (0.12*(19*95.50));
break;
case 'B':
if (tankSize == 5)
amount = (5*77.50) + (0.09*(5*77.50)) + (0.09*(5*77.50));
else if (tankSize == 14.2)
amount = (14.2*77.50) + (0.09*(14.2*77.50)) + (0.09*(14.2*77.50));
else if (tankSize == 19)
amount = (19*97.50) + (0.12*(19*97.50)) + (0.12*(19*97.50));
break;
case 'H':
if (tankSize == 5)
amount = (5*79.50) + (0.09*(5*79.50)) + (0.09*(5*79.50));
else if (tankSize == 14.2)
amount = (14.2*79.50) + (0.09*(14.2*79.50)) + (0.09*(14.2*79.50));
else if (tankSize == 19)
amount = (19*99.50) + (0.12*(19*99.50)) + (0.12*(19*99.50));
break;
default:
printf("Unable to read tankSize\n");
}
amount+=20; //Delivery charge
printf("Total price to be paid for refilling the gas (including GST) is INR: %f", amount);
}
Above code doesn't work.
However, changing the data type of tankSize, amount, and the second parameter to totalPrice to double from float cause the code to work.
Why do the integer inputs (5 and 19) work in all cases but input 14.2 works only when data type is double?
In this if statement
you are comparing a float number stored in the variable
tankSizeof the typefloatwith a double constant14.2.Double values have higher precision than float values.
You should compare two float values
Using the suffix
fmakes the floating constant of the typefloat.From the C Standard (6.4.4.2 Floating constants)
That is instead of the floating constant
14.2of the typedoubleyou should use the floating constant14.2fof the typefloat.Here is a demonstration program
The program output is