New to C, and all math calculations are slightly turned off

I'm in the programming class where we just switched from python to C. I have a bit of a problem with this, since C doesn't seem to do the math with ease, which is what python does, or I'm missing something when it comes to comes to math in C.

For my homework, I am writing a program that collects how many miles per gallon user’s car, how much gas they cost per gallon, and how many miles they travel every 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 values ​​of 24 for "mpg", 3.00 for "gas_price" and 1000 for miles, the total is $ 123.00. This is incorrect and two dollars less than the actual price. When you take ((1000/24) * 3.00), you should get 125 points. I added a line to print all the values ​​to see what C used for the formula on line 23, and while mpg and gas_price are correct, miles are displayed as having a value of 1,074,266,112. I know what should be here some kind of mistake, as this will lead to an exit for more than $ 2, but I can not help but think about it.

I apologize for the length of the question, but I wanted to be as specific as possible, and I am completely fixated on why C reads this way.

+8
c math
source share
4 answers

Here you do integer division:

 miles / mpg * gas_price 

First pass one of the two operands to double :

 (double)miles / mpg * gas_price 

Integer division truncates the fractional part. This is why your numbers are disabled.


You have another error:

 printf("%d %d %d", mpg, gas_price, miles); 

printf format specifiers do not match operands. It should be:

 printf("%d %f %d", mpg, gas_price, miles); 
+14
source share

This expression:

 miles / mpg * gas_price 

analyzed as

 (miles / mpg) * gas_price 

where division is performed before multiplication. Both division operands are integers, so C gives you an integer (truncated) result. To get this to work with floating point, do the following:

 1.0 * miles / mpg * gas_price 
+4
source share

Change int mpg, miles; on double mpg, miles; . The problem is that miles/mpg uses integer division, which gives 41 instead of 41.66 ....

+1
source share

The integer division miles / mpg will lose some precision. You also have a printf format specifier mismatch in your last line - you should use %f or something related to it, and not %d when printing gas_price .

0
source share

All Articles