#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <math.h>
usingnamespace std;
int main()
{
//My Variables
float gasPrice;
float moneySpent;
float litersOfGas;;
float kilometers;
float fuelEfficiency;
//Dialogue
cout<< "What is the current gas price?\n";
cin>> gasPrice;
cout<< "How much money did you spend on gas?\n";
cin>> moneySpent;
litersOfGas = moneySpent / gasPrice;
cout<< "You have filled up approximately - " << litersOfGas << " - liters of gas.\n";
cout<< "\n";
cout<< "How many kilometers did you travel?\n";
cin>> kilometers;
fuelEfficiency = kilometers / litersOfGas;
//Final Answer
cout<< "Your fuel efficiency is " << fuelEfficiency << "KPG." << endl;
return 0;
}
I don't know exactly why you got negative numbers. I'm currently assuming it had something to do with declaring the variables while also performing an operation?
Ok, I think the issue (WARNING: Noob Opinion) is that you are trying to assign a value to fuelEfficiency before it the two variables being used in the operation to define it have any user inputted value. By doing that, you make the system pull values out of memory to apply to kilometers. Actually, you're doing that for four variables but they are overwritten before it makes a difference for the the litersOfGas variable. If you made a function I suppose that method would fly.
I recommend you taking tutorial from this site, it will help you with basics of C++.
Anyway, in programming(not only C++), you have to remember, that program will be executed line by line, in strict order that you create.
Having this in mind, if you go through your program, you will see quite a few bugs -
you instantly declare litersOfGas = moneySpent / gasPrice;
but you haven't told program what are values of moneySpent and gasPrice!
You actually do it later, but variables were set before.
TheCooperFellow got this right, this is how you should do it - first assign some values to variables, and then make operations on them(like addition or division).
As for negative values, it's just some random trash memory.
Whoa, thanks a lot for the replies guys!!
I am a complete newbie to C++, just picked up a C++ for dummies book and haven't reached the 100th page yet.
This community is so engaging - it's awesome! Thanks again!