TPS 4: Branching
- Due Feb 24, 2021 by 10am
- Points 1
- Submitting a file upload
- File Types doc and docx
- Available after Feb 24, 2021 at 9am
Recall the program we wrote that asks the user for m , x , and b and then solves for y in the equation y=mx+b :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Purpose: Solves for y in y=mx*b. #include <iostream> using namespace std; int main(){ float m, x, b, y; // Get the user's input. cout << "Please enter m, x, and b (separated by spaces): "; cin >> m >> x >> b; // Solve for y. y = m * x + b; // Output result. cout << "y = " << y << endl; return 0; } |
Suppose we want to allow the user to select to solve for y or x . If they want to solve for y , we ask for values for m , x , and b. If they want to solve for x , however, we will ask for the value of m , y , and b. Here is the mostly completed revised program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
// Purpose: Solves for x or y in y=mx*b. #include <iostream> using namespace std; int main(){ char varToSolveFor; float m, x, b, y; // Find out what the user wants to solve for. cout << "Which would you like to solve for, [x] or [y]? "; cin >> varToSolveFor; // Solve for y. if(_____________){ // Get the user's input. cout << "Please enter m, x, and b (separated by spaces): "; cin >> m >> x >> b; // Solve for y. y = m * x + b; // Output result. cout << "y = " << y << endl; // Solve for x. } else if(_____________){ // Get the user's input. cout << "Please enter m, y, and b (separated by spaces): "; cin >> m >> y >> b; // Solve for x. x = (y-b)/m; // Output result. cout << "x = " << x << endl; // Invalid input. } else { cout << "Invalid option." << endl; } return 0; } |
Specify what goes in the blanks on lines 14 and 26.
After we've completed the group share portion, upload a copy of your updated TPS document.