I have been working on this program to calculate the Kinetic Energy of mass at velocity. I am having problems with my return value from the function to the main. I got the passing from main to function. Here is the code, can anyone tell me what im doing wrong?
It gives me an error that kenergy variable is being used without initializing. I clearly have initialized it in the main, and the function.
Please, please, please help. I hate that I can't figure this out.
You need to receive a return value into something if you want to keep it. It's not enough to define it and declare it, you have make an assignment into the receiving variable.
Im not arguing that it works, i see that it does, i just can't wrap my head around it, and that means more that having the answer. Oh yeah, thanks for the answer. lol
As Roberts said, you need a variable to receive the returned value from kinetic(mass, velocity). The return value from your function is copied into this variable. To reiterate vin's recommendation, read up on variable scope, pass by value, pass by reference etc.
Here's your code with a couple of variable names changed to demonstrate what I mean.
#include <iostream>
#include <cmath>
usingnamespace std;
double kinetic(double mass, double velocity)
{
double result;
result = 0.5 * mass * velocity * velocity;
return (result);
}
int main ()
{
double kenergy;
double velocity;
double mass;
cout<<"Please enter the mass of an object in kilograms: ";
cin>>mass;
cout<<"Please enter the velocity of an object in meters per second: ";
cin>>velocity;
kenergy = kinetic(mass, velocity);
cout<<"The Kenetic Energy for "<<mass<<" kilos, at "<<velocity<<" meters per second is; "<<kenergy;
system ("pause");
return 0;
}
You could also do this:
cout<< "The Kenetic Energy for " <<mass<< " kilos, at " << velocity << " meters per second is: " << kinetic(mass, velocity);
You could also do this with your kinetic(...) function: