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.
c math
Batteries
source share