Please use code tags.
There should be no semi-colon after the condition following an (else)
if
.
else if (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;
} else if ( 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
int
egers, perhaps you would enter
1
to add,
2
to subtract, and so forth.
Here is a corrected version of your code:
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
|
#include <iostream>
using namespace std;
int num1, num2, result, function;
int const add = 1, subtract = 2, multiply = 3, divide = 4;
int main()
{
cout << "Please enter the first number: ";
cin >> num1;
cout << "Please enter the second number: ";
cin >> num2;
cout << "Please enter function (1 for add, 2 for subtract, 3 for multiply, 4 for divide ):";
cin >> function;
if ( function == add ) {
result = num1 + num2;
cout << num1 << " plus " << num2 << " is equal to: " << result << ".\n";
} else if ( function == subtract ) {
result = num1 - num2;
cout << num1 << " minus " << num2 << " is equal to: " << result << ".\n";
} else if ( function == multiply ){
result = num1 * num2;
cout << num1 << " times " << num2 << " is equal to: " << result << ".\n";
} else if (function == divide) {
result = num1 / num2;
cout << num1 << " divided by " << num2 << " is equal to: " << result << ".\n";
}
return 0;
}
|