Well, I'm trying to make my first program, in this case a calculator.
But when i run it, i enter the first number, and then (per example) - and then it closes... but i have no idea why.
could you please help me??
#include <iostream>
usingnamespace std;
int Plus() {
int num1;
int num2;
cout << "The Answer is: " << num1 + num2 << endl;
cout << "Press ENTER to continue";
getchar();
return 0;
}
int Min() {
int num1;
int num2;
cout << "Press ENTER to continue";
getchar()
return 0;
}
int Divide() {
int num1;
int num2;
cout << "Het antwoord is: " << num1 / num2 << endl;
cout << "Press ENTER to continue";
getchar();
return 0;
}
int Multiply() {
int num1;
int num2;
cout << "Het antwoord is: " << num1 * num2 << endl;
cout << "Press ENTER to continue";
getchar();
return 0;
}
int main() {
int num1, num2;
int i;
cout << "Enter the sum." << endl;
cin >> num1;
cin >> i;
cin >> num2;
if(i == '+')
Plus();
elseif (i == '-')
Min();
elseif (i == '/')
Divide();
elseif (i == '*')
Multiply();
else {
cout << "The sum is invalid." << endl;
cout << "Press ENTER to continue..." << endl;
getchar();
}
}
thanks for looking at my post, but it doesn't work. It still only lets me enter the first number and then the operator, and then the console shuts down(while i still have to enter the 3rd number).
Do you have another idea that could solve the problem?
First you need to add a semicolon on line 17.
Then read some tutorial on C++ function parameters.
The variables num1 & num2 you used in main() and all other functions are unrelated, except for having the same variable names. You might want to also read about function scope.
And what about this? i read the tutorial at the documentation part( http://cplusplus.com/doc/tutorial/functions/) so this is what i got now, is it better?(it still does the same as before(doesn't let me enter the last number))
#include <iostream>
usingnamespace std;
int Plus(int a, int b)
{
int r;
r=a+b;
return (r);
}
int Min(int a, int b)
{
int r;
r=a-b;
return (r);
}
int Divide(int a, int b)
{
int r;
r=a/b;
return(r);
}
int Multiply(int a, int b)
{
int r;
r=a*b;
return (r);
}
int main()
{
int num1, num2;
int i;
cout << "Enter the sum." << endl;
cin >> num1 >> i >> num2;
switch (i) {
case'+': cout << "Result: " << Plus(num1,num2);
break;
case'-': cout << "Result: " << Min(num1,num2);
break;
case'*': cout << "Result: " << Multiply(num1,num2);
break;
case'/': cout << "Result: " << Divide(num1,num2);
break;
default : cout << "The sum is invalid." << endl;
system("PAUSE");
return 0;
}
}