-
Function not calling
Hey, so I've been just practicing writing some simple programs trying to use loops and calling on functions. So I wrote this thing up real quick, and tried to get it to run, and I don't understand what's wrong. It's compiling with no errors or warnings, but every time I run it, the program just adds the two numbers no matter what I do. So I feel really stupid, but here it is. I've been staring at it for about 20 minutes making sure my FOR/ELSE loop is good and I've not forgotten anything obvious (I hope!)
I wrote an add function and a subtract function. I know you guys can probably figure out what I'm trying to do, but this is an explanation of how I see it running.
1. The user selects whether he wants to add or subtract.
2. Based on the selection it's a for loop that calls on the correct function.
3. The functions imports the stored numbers, does the math and posts it
4. The program finishes.
Code:
#include <iostream>
using namespace std;
//subtract function
int Subtract(int alpha, int omega){
cout<<"The total of " << alpha << " minus " << omega << " is...\n";
cout<< alpha - omega << endl;
return 0;
}
//addition function
int Additup(int apple, int orange){
cout<<"The total of " << apple << " plus " << orange << " is...\n";
cout<< apple + orange << endl;
return 0;
}
//main function time!
int main(){
int choice, num1, num2, num3;
cout << "1 for addition, 2 for subtraction: ";
cin >> choice;
cin.ignore();
if(choice = 1){
cout<<"Enter the two numbers with a space inbetween then press enter: ";
cin >> num1;
cin >> num2;
num3=Additup(num1,num2);
}
else{
cout<<"Enter the two numbers then press enter: ";
cin >> num1;
cin >> num2;
num3=Subtract(num1, num2);
}
return 0;
}
Also, one more thing. I understand that the code is both A) probably very inefficient for it's purpose, and B) might be a little sloppy. I know this, and I'm just working on the foundations right now. Thanks again for help!
-
>> if(choice = 1)
Careful! ;)
-
Bah! I'm an idiot! Thank you!
An explanation for the solution. My original if loop was this.
Code:
if(choice = 1){
cout<<"Enter the two numbers with a space inbetween then press enter: ";
cin >> num1;
cin >> num2;
num3=Additup(num1,num2);
}
The first line of that my operator was supposed to be if(variable equals value) { I did a Noob mistake and forgot that the relational operator for equal is not 1 equal sign, but two signs. So a comparison of right and wrong was....
Wrong..
if(choice = 1){
Right
if(choice == 1){
Thanks Seba
-
Which compiler are you using?
If it's gcc, then try
g++ -Wall prog.cpp
For visual studio (recent flavours)
cl /w4 prog.cpp
-
Or more generally, project properties -> C/C++ -> General -> Warning Level -> Set to 4.