I'm in a programming class where we have just switched from python to C. I'm having a bit of trouble with it, as C doesn't seem to perform mathematical operations with the ease that python does, or I'm missing something when it comes to math in C.
For my homework, I'm writing a program that collects how many miles to a gallon user's car gets, how much their gas costs per gallon, and how many miles they drive each month. The program then tells them how much they can expect to pay for gas for the current month. My current code is as follows:
#include <stdio.h>
int main () {
int mpg, miles;
double gas_price;
printf("How many miles per gallon does your car get?\n");
scanf("%d", &mpg);
printf("What is the price of gasoline per gallon?\n");
scanf("%lf", &gas_price);
printf("How many miles do you drive in a month?\n");
scanf("%d", &miles);
printf("The cost of gas this month is $%.2lf\n", miles / mpg * gas_price);
printf("%d %d %d", mpg, gas_price, miles);
return 0;
}
When I run the program with the values 24 for "mpg", 3.00 for "gas_price", and 1000 for miles, the total comes to $123.00. This isn't correct, and is about two dollars less than the actual price. When you take ((1000 / 24) * 3.00), you should get 125 even. I added a string to print out all the values to see what C was using for the formula in line 23, and while mpg and gas_price are correct, "miles" shows up as having a value of 1,074,266,112. I know there must be some error here, as this would throw the result off way more than 2 dollars, but I can't help but think it's related.
I apologize for the length of the question, but I wanted to be as specific as possible, and I'm completely stumped as to why C is reading this in so strangely.
You're doing integer division here:
miles / mpg * gas_price
Cast one of the two operands to a double
first:
(double)miles / mpg * gas_price
Integer division will truncate the fractional part. That's why your numbers are off.
You have another error here:
printf("%d %d %d", mpg, gas_price, miles);
Your printf
format specifiers don't match the operands. It should be:
printf("%d %f %d", mpg, gas_price, miles);
This expression:
miles / mpg * gas_price
is parsed as
(miles / mpg) * gas_price
where the division is done before the multiplication. Both operands of the division are integers, so C gives you an integer (truncated) result. To force this to be a floating point calculation, do this:
1.0 * miles / mpg * gas_price
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With