Hello
I'm trying to create a calculator that takes a keyboard-entered variable, followed by a choice of variable, a value for that variable, then a calculation, using one of two expressions. The expression used depends on the chosen variable.
It should read something like this:
Please enter a mass
5
Will you enter [S]peed or [M]omentum?
s
Please enter the speed
10
A mas of 5kg with speed of 10m/s has kinetic energy of 250J.
The program I have so far works until the calculation, where I get a runtime error. If I chose to enter a speed, it says the variable representing momentum is being used without being initialised. If I chose momentum, the speed variable gets the same error. I've tried multiple variations, but it keeps happening.
I don't understand what is wrong with it, and I'm not sure if I'm linking the expressions to the statements correctly..Code:#include <iostream> using namespace std; int main () { //variable declarations and initialisation double en_k1; double en_k2; double mass; double vel; double mom; //prompt and read mass cout << "Please enter the mass (kg):" << endl; cin >> mass; //prompt for choice of speed or momentum cout << "Are you going to enter a [S]peed or a [M]omentum?" << endl; char choice; cin >> choice; switch (choice){ case 's': case 'S': cout << "Please enter the speed (m/s)." << endl; cin >> vel; break; case 'm': case 'M': cout << "Please enter the momentum (kgm/s)" << endl; cin >> mom; break; default: cout << "You entered a mass of " << mass << "kg, but your choice of speed or momentum was not a valid choice." << endl; } //conditional read and calculate energy if (vel){ en_k1 = 0.5 * mass * (vel * vel); } else if (mom){ en_k2 = mom / (2 * mass); } //print result cout << "A mass of " << mass << "kg with a speed of " << vel << "m/s has a kinetic energy of " << en_k1 << "J." << endl; cout << "A mass of " << mass << "kg with a momentum of " << mom << "kgm/s has a kinetic energy of " << en_k2 << "J." << endl; //spit if invalid input //sign off politely cout << "Thank you for using the kinetic energy calculator." << endl; } //end of main()
Could anyone offer any help?
Thanks.



LinkBack URL
About LinkBacks



