mardi 26 mai 2020

How would I clean up these If Statements?

if (calculation == "help") {
    cout << "add, subtract, multiplication, divide\nsquare root, sin, cos, power\n";
}
else if (calculation == "add") {
    cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;
}
else if (calculation == "subtract") {
    cout << num1 << " - " << num2 << " = " << num1 - num2 << endl;
}
else if (calculation == "multiplication") {
    cout << num1 << " x " << num2 << " = " << num1 * num2 << endl;
}
else if (calculation == "divide") {
    cout << num1 << " / " << num2 << " = " << num1/ num2 << endl;
}
else if (calculation == "square root") {
    cout << "The square root of the first number is " << sqrt(num1) << ". The square root of the second number is " << sqrt(num2) << "." << endl;
}
else if (calculation == "sin") {
    cout << "The sine of the first number is " << sin(num1) << ". The sine of the second number is " << sin(num2) << "." << endl;
}
else if (calculation == "cos") {
    cout << "The cosine of the first number is " << cos(num1) << ". The cosine of the second number is " << cos(num2) << "." << endl;
}
else if (calculation == "power") {
    cout << num1 << " to the power of " << num2 << " = " << pow(num1, num2) << endl;
}```

I have an idea for fixing these if statements, such as creating a map or a dictionary. I don't believe you can use strings with switch statements in C++ either. Any help is much appreciated!

Aucun commentaire:

Enregistrer un commentaire