+ 1
Why wont it miltiply correctly
#include <iostream> using namespace std; int main() { int a, b; cout << "Enter a number \n"; cin >> a; cout << "Enter another number \n"; cin >> b; int sum=a+b; if (a, b =a+b) cout << sum; int product=a*b; if (a, b=a*b) cout<<product; return 0; }
3 Answers
+ 7
"but I was using them because I wanted to let the user choose to add or multiply the two numbers"
It demands to implement your solution differently. For example
#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "Enter a number \n";
cin >> a;
cout << "Enter another number \n";
cin >> b;
int choice;
cout << "1) Add\n"
<< "2) Multiply\n";
cin >> choice;
switch (choice) {
case 1:
cout << "Sum: " << a+b << endl;
break;
case 2:
cout << "Product: " << a*b << endl;
break;
default:
cout << "Wrong choice!\n";
}
return 0;
}
Output:
Enter a number
5
Enter another number
4
1) Add
2) Multiply
2
Product: 20
+ 7
Because what you've done inside `if` statements have nothing to do with summation and multiplication and mess everything after the first `if` statement.
#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "Enter a number \n";
cin >> a;
cout << "Enter another number \n";
cin >> b;
int sum=a+b;
cout << "Sum: " << sum << endl;
int product=a*b;
cout << "Product: " << product;
return 0;
}
Output:
Enter a number
5
Enter another number
4
Sum: 9
Product: 20
_____
For more info about the comma operator visit: https://en.cppreference.com/w/c/language/operator_other#Comma_operator
+ 2
I see what you're saying but I was using them because I wanted to let the user choose to add or multiply the two numbers