int num1, num2, result, function, add, subtract, multiply, divide;
int main()
{
cout << "Please enter the first number: ";
cin >> num1;
cout << "Please enter the second number: ";
cin >> num2;
cout << "Please enter function ( add, subtract, multiply, float divide ):";
cin >> function;
if ( function == add )
cout << num1 << " plus " << num2 << " is equal to: " << result << ".\n";
result = num1 + num2;
else if ( function == subtract );
cout << num1 << " minus " << num2 << " is equal to: " << result << ".\n";
result = num1 - num2;
else if ( function == multiply );
cout << num1 << " times " << num2 << " is equal to: " << result << ".\n";
result = num1 * num2;
else ( function == divide );
cout << num1 << " divided by " << num2 << " is equal to: " << result << ".\n";
result = num1 / num2;
return 0;
}
here is my code but it keeps returning
||=== Build: Debug in Calculator (compiler: GNU GCC Compiler) ===|
C:\Users\thein_000\Desktop\C or C++ programs\Calculator\main.cpp||In function 'int main()':|
C:\Users\thein_000\Desktop\C or C++ programs\Calculator\main.cpp|24|error: 'else' without a previous 'if'|
C:\Users\thein_000\Desktop\C or C++ programs\Calculator\main.cpp|27|error: 'else' without a previous 'if'|
C:\Users\thein_000\Desktop\C or C++ programs\Calculator\main.cpp|30|error: 'else' without a previous 'if'|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
There should be no semi-colon after the condition following an (else) if. elseif (condition) { ... }
You need to add braces around the code you want to run following an if (or any other compound statement):
1 2 3 4
if (function == add) {
cout << num1 << " plus " << num2 << " is equal to: " << result << ".\n";
result = num1 + num2;
} elseif ( function == subtract ) { ... }
The = sign is called the assignment operator, because it assigns the value of the stuff on the right to the stuff on the left. In your code, you are not writing equations which are true all the time. Since your code runs sequentially from top to bottom, statements like
1 2
cout << num1 << " plus " << num2 << " is equal to: " << result << ".\n";
result = num1 + num2;
Print the value of result before assigning it a value, which means your code is broken.
You do this in each case. You do that with add, multiply, subtract, and divide, too.
Since they are all integers, perhaps you would enter 1 to add, 2 to subtract, and so forth.