This is my first post so I hope I did this all right. My teacher wants me to create a force calculator that either outputs a calculation with acceleration set to 9.8 or acceleration specified. When I run this with the choice input as 1, it does what I want to. When I run it as choice 2, it runs the first if statement, than the second if statement. Entering a 0 or 4 doesn't work either because it just runs a calculator even though I want it to output an error message. Any help is greatly appreciated. Thank you!
You could change the if for choice 2 and 3 to elseif, then have a plain else to catch the bad input.
1 2 3 4 5 6 7 8 9 10 11 12 13
if (choice == 1) {
//call a function to do this
}
elseif (choice == 2) {
//call a function to do this
}
elseif (choice == 3) {
//call a function to do this
}
else {
std::cout << " Error: incorrect input\n";
std::system ("pause"); // try to avoid using system anything
}
Alternatively use a switch with a default: case. This has a loop too, as an improvement :+)
bool Quit = false;
while (!Quit) {
// show menu
// get menu selection
switch (choice) {
case 1:
//call a function to do this
break;
case 2:
//call a function to do this
break;
case 3:
// user wants to quit
Quit = true;
break;
default: // bad input
std::cout << " Error: incorrect input\n";
break;
} // end switch
} // end while
You are re-declaring your variables for forcemass and acc.
If you have a constant like 9.8, make it a const variable and use that name in the code: constdouble acc = 9.8;
Delay the declaration until you have a sensible value to assign to it, or initialise the variable with something:
1 2 3 4 5 6
constdouble acc = 9.8;
double mass = 1.0; // always initialise even when getting input straight away,
// zero not necessarily a good choice.
std::cin >> mass;
double force = mass * acc; // declaration calc and assignment all at once
I sometimes advise initialising a variable with a wacky value: Then hopefully the lack of assigning it a proper value might be more apparent later when printing say:
1 2 3 4
int percent = 999; // valid range 0 to 100
//...
//...
std::cout << "percent is " << percent << "\n"; // oops, I see what I didn't do
Prefer double rather than float. float precision is easily exceeded. double is the default for this reason.