Note that there are some explanatory texts on larger screens.

plurals
  1. PONew to C, and all the math calculations are slightly off
    primarykey
    data
    text
    <p>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.</p> <p>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:</p> <pre><code>#include &lt;stdio.h&gt; int main () { int mpg, miles; double gas_price; printf("How many miles per gallon does your car get?\n"); scanf("%d", &amp;mpg); printf("What is the price of gasoline per gallon?\n"); scanf("%lf", &amp;gas_price); printf("How many miles do you drive in a month?\n"); scanf("%d", &amp;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; } </code></pre> <p>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.</p> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload