So i'd like to write the formula
KE = 1 / 2mv^2
in C++, creating a function that calculates a value using the kinetic energy equation. But I'm not entirely
sure how to go about showing 1 / 2
. Wouldn't I have to make it a double
because if I represent 1 / 2
as an integer it'll just display 5
? What the compiler is really seeing would be 0.5
, from which the zero is cut off? Here is the piece of code I have so far to calculating this equation: double KE = 1/2*mvpow(KE,2); Here's my code and what i'm trying to do.
It's giving me 0
instead of 25
when I use the test values of 2
and 5
.
//my protyped function kineticEnergy
double kineticEnergy(int m, int v);
int main(){
int m; // needed to pass a value into kineticEnergy function
int v; // needed to pass a value into kineticEnergy function
cout << "Enter the mass " << endl;
cin >> m;
cout << "Enter the velocity" << endl;
cin >> v;
int results = kineticEnergy(m,v);
cout << "The total kinetic energy of the object is " << results << endl;
return 0;
} // end of main
// ##########################################################
//
// Function name: kineticEnergy
//
// Description:This will grab input from a program and calculate
// kinetic energy within the function
// ##########################################################
double kineticEnergy(int m, int v){
double KE = 1/2*m*v*pow(KE,2); // equation for calculating kinetic energy
return KE;
} // end of kinetic energy
Yes, 1 and 2 are integer constants, so 1/2
gives you 0
, which is the result of the integral division of 1 by 2.
What you want is this (assuming "m*v*pow(KE,2)
" is correct):
double KE = 1.0/2.0*m*v*pow(KE,2);