I’m starting to learn C programming and am having an issue with this code:
#include <stdio.h>
float jobPrice (int numberOfPages, float pricePerSheet, float pricePerPlate, int numberOfCopies)
{
return (((pricePerPlate * numberOfPages) + ((numberOfPages/2)*numberOfCopies*pricePerSheet) + (numberOfCopies*2)) * 1.175f);
}
float colourPrinting (int numberOfPages, int numberOfCopies)
{
return jobPrice(numberOfPages, 0.04f, 28.00f, numberOfCopies);
}
int main ()
{
printf("%f\n", colourPrinting(32, 1000));
return 0;
}
The value that should be printed is 4154.8 but my program is printing 4154.799805. I’ve debugged the code and it seems that when calling jobPrice with the pricePerSheet parameter of 0.04f, it’s changing to 0.0399999991.
Any help would be appreciated.
Use
doubleinstead offloat. Afloatprovides at most 7 significant decimal digits, and your printing format is trying to extract 10, which leads to garbage. Or print just 2 decimal places; that will give you the answer with 6 significant figures.See ‘What Every Computer Scientist Should Know About Floating-Point Arithmetic’ for more information.