SureShoy SureShoy - 1 month ago 12
C Question

show decimal using C

I'm trying to show the decimal points after the number

#include <stdio.h>

int main() {

int weight;
int miles;
int price;

printf("Enter the packages weight \n");
scanf("%d", &weight);

printf("Enter how many miles to ship the package \n");
scanf("%d", &miles);

if(weight <= 15) {
price = 15;
}
else {
price = (15 + ((weight - 15) * .5 ));
}
if(miles % 500 == 0) {
price += (miles / 500 * 10);
}
else {
price += ((miles / 500 )* 10) + 10;
}


printf("It will cost $%d to ship an item weighing %d pounds %d miles \n", price, weight, miles);
return 0;
}


for the
price = (15+((weight-15)*.5));
When I plug in the numbers outside of the console it shows the decimal places. I'm probably missing the most simple thing...

Answer

You should change the data type of the variable price to float (or double) if you wish to store some fractional part in it.

Also, since miles / 500 may create some decimal part (and miles itself can be floating-point!), it should also be made float or double.

Finally, in the printf arguments, do not forget to change the format specifier %d.

Prefer to use a floating-point data type for all the variables involved in some computation that might yield fractional numbers as it will be more comprehensible and if you wish to not see the decimal part in the output, then set the precision to 0 (%.0f).

Comments