This question already has an answer here:
This is a suppposed to be simple calculator which can plus, minus, mulyiply or divide two numbers that are input into the console (int a, b). The problem is probably with my if / else statemnts. Even though I input "Minus" , "Multiply" or "Divide" into the console, the operator (std::string operator) is always set to "plus", thus adding the two numbers even though that was not my desired operator.
Ive tried removing the [int plus();] function alltogether to see the result, then the default and fixed operator changed to minus.
#include <iostream>
// the problem is probably at [void core();]
std::string operation;
int a;
int b;
class common {
public:
void print() {
std::cout << "a: ";
std::cin >> a;
std::cout << "b: ";
std::cin >> b;
}
};
int plus() {
common plus1;
plus1.print();
int ans = a + b;
std::cout << "ANS: " << ans << "\n";
return a + b;
}
int minus() {
common minus1;
minus1.print();
int ans = a - b;
std::cout << "ANS: " << ans << "\n";
return a - b;
}
int multiply() {
common multiply1;
multiply1.print();
int ans = a * b;
std::cout << "ANS: " << ans << "\n";
return a * b;
}
int divide() {
common divide1;
divide1.print();
int ans = a / b;
std::cout << "ANS: " << ans << "\n";
return a / b;
}
void core() {
std::cout << "\nplus / minus / multiply / divide\n"
<< "operation: ";
std::cin >> operation;
if (operation == "plus" or "Plus") {
plus();
}
else if (operation == "minus" or "Minus") {
minus();
}
else if (operation == "multiply" or "Multiply") {
multiply();
}
else if (operation == "divide" or "Divide") {
divide();
}
else {
std::cout << "Invalid Operation!\n";
}
}
int main() {
for (int i = 0; i < 99; i++) {
core();
}
}
When i set [std::string operation] as "multiply" through [std::cin >> operation], i expected the [multiply();] function to be called but instead, [plus();] function is called no matter what operator i set.
Aucun commentaire:
Enregistrer un commentaire