Hi,im building a Flight calculator program, which calaculates the fuel consumption needed for a plane. Im using functions and the program runs fine, but when I input data it comes with a strange number like this 3.067+e45. I cant figure out whats wrong.
void fuel (float & dist) //function
{
cout<<"Enter the distance of flight "<<endl;
cin>>dist;
}
void distance(float dist, float & time, float & time2)
{
time = dist/300; // Speed is constant 300mph
time2 = (time - 0.30)*60; //30 minutes is needed to get to the top level
cout<< " the flight will last "<<time<<" hours "<<endl; // output
}
void Altitude(float time, float time2, float altlevel) //function
{
float Level1,Level2,Level3,Level4,Level5,Level6,Level7,Level8,Level9; // each level goes from 0 to 40,000 feet,
your using float, float is very high precision and the results are too fine for comparison...I would recommend you use double or int or unsigned int which ever works for ya.
altlevel is actually not initialized. The data that you see there is garbage. C and C++ don't do any garbage management for you; they don't rewrite memory when you declare a variable. Whatever was in the spot now marked by your new data is what you see if you print the variable.
The problem with altlevel not being initialized is that you didn't send it by reference, so whatever changes you did inside the void Altitude Function are not being carried back to main(). Just change the
void Altitude(float time, float time2, float altlevel)
to void Altitude(float time, float time2, float& altlevel)
void Altitude(float time, float time2, float altlevel)
to
float Altitude(float time, float time2, float altlevel)
then you can place a return altlevel. But then you need to assign the value to altlevel like this: altlevel = Altitude(speed, altspeed, altlevel); which then there's no point in sending altlevel over in the first place. The method by adding the & to the function definition sends the variable by reference and changes the value in the calling function. This will be important when you need to deal with functions changing and having to return more than one item.
When it comes to a function just changing one variable you should return a value instead of using the pointer method. This is incase you want to do something like use this as part of the Travelling Salesmen problem and you are saving the altlevel into a vector or array for later comparison. You can actually declare both versions of your Altitude(...) fucntion like this: