c++ - Should I use goto statement here? -
a fine gentleman told me goto statements bad, don't see how can not use here:
int main() { using namespace std; int x; int y; int z; int a; int b; calc: //how can here, without using goto? { cout << "to begin, type number" << endl; cin >> x; cout << "excellent!" << endl; cout << "now need type second number" << endl; cin >> y; cout << "excellent!" << endl; cout << "now, want these numbers?" << endl; cout << "alt. 1 +" << endl; cout << "alt. 2 -" << endl; cout << "alt. 3 *" << endl; cout << "alt. 4 /" << endl; cin >> a; if (a == 1) { z = add(x, y); } if (a == 2) { z = sub(x, y); } if (a == 3) { z = mul(x, y); } if (a == 4) { z = dis(x, y); } } cout << "the answer math question "; cout << z << endl; cout << "do want enter question?" << endl; cout << "type 1 yes" << endl; cout << "type 0 no" << endl; cin >> b; if (b == 1) { goto calc; } cout << "happy trails!" << endl; return 0; } it calculator, can see. also, if want, can suggest better way (if exists) let user choose operation (+ - * /). header files under control. apologize lot of cout statements.
here cleaned-up , formatted version using do/while loop structure:
using namespace std; int main() { int x, y, z, a, b; { cout << "to begin, type number" << endl; cin >> x; cout << "excellent!" << endl; cout << "now need type second number" << endl; cin >> y; cout << "excellent!" << endl; cout << "now, want these numbers?" << endl; cout << "alt. 1 +" << endl; cout << "alt. 2 -" << endl; cout << "alt. 3 *" << endl; cout << "alt. 4 /" << endl; cin >> a; if (a == 1) { z = add(x, y); } else if (a == 2) { z = sub(x, y); } else if (a == 3) { z = mul(x, y); } else if (a == 4) { z = dis(x, y); } cout << "the answer math question "; cout << z << endl; cout << "do want enter question?" << endl; cout << "type 1 yes" << endl; cout << "type 0 no" << endl; cin >> b; } while (b != 0); cout << "happy trails!" << endl; return 0; }
Comments
Post a Comment