Archived

This topic is now archived and is closed to further replies.

RogueZero

I need some help on a simple C++ math program

Recommended Posts

Ok i just started learning C++ and its my first language ive ever learned other than some simple things in Qbasic a long time ago. I''m learning C++ out of a online ebook called teach yourself C++ in 21 days. I''m currently on the third day and I learned a little about functions. I learn better if I ask questions and have other more knowledgable people help me out than if i just study a book. I can use a simple function to make a program add multiple divide or subtract two numbers but I cant let the person running the program decide what simple math function to do with those numbers. This is what i got so far:
#include <iostream>
int multiply (int x, int y)
{
cout << " Multiplied " << x << " and " << y << "\n";
return (x*y);
}
int main()
{
int a, b, c;
cout << " Enter 2 numbers: ";
cin >>a;
cin >>b;
c=multiply(a,b);
cout << "Heres the answer to your multiplication question: " << c;
cin >> c;
return 0;
}
can someone help me make this program ask the user what to do with the numbers then do it to the numbers using this simple type of source code. I''m a newb so keep it as simple as possible.

Share this post


Link to post
Share on other sites
Something like:


#include <iostream>

int Multiply(...)
{
...
}

int Divide(...)
{
...
}

int Add(...)
{
....
}

int main()
{
int a, b, c, d;
std::cout << " Enter 2 numbers: ";
std::cin >> a;
std::cin >> b;

std::cout << " Multiply(1)? Divide(2)? Add(3)? " << std::endl;
std::cin >> d;

if(d == 1) { c = Add(...) };
if(d == 2) { c = Divide(...) };
if(d == 3) { c = Add(...) };

std::cout << "Heres the answer to your question: " << c;
std::cin >> c;
return 0;
}


[edited by - Orb on July 27, 2003 9:57:21 PM]

Share this post


Link to post
Share on other sites

Try something like this:


#include <iostream>
/*************************************
* *
*************************************/

int multiply (int x, int y)

{
cout << " Multiplied " << x << " and " << y << "\n";
return (x*y);

}
/*************************************
* *
*************************************/


char simpleMenu(void)
{
char choice;
cout<<"1: Multiply\n";
cout<<"2: Add\n";
cout<<"3: Divide\n";
cin>>choice;
return choice;

};
/*************************************
* *
*************************************/

int main(void)
{

int a, b, c;
cout << " Enter 2 numbers: ";
cin >>a;
cin >>b;
char men = simpleMenu();

switch(men)
{
case ''1'':{c=multiply(a,b);};
break;
case ''2'':{cout<<"do another function\n";};
break;
case ''3'':{cout<<"do another function\n";};
break;
default: exit(1);
};

cout << "Heres the answer to your multiplication question: " << c;
return 0;
}

Share this post


Link to post
Share on other sites
Look at Day 7 of your book (I think it's called 'More Program Flow') to learn about control statements like if, elseif, else, and switch. You should be able to figure out how to tie in the other stuff you need once you've looked into them.

[edited by - SysOp_1101 on July 27, 2003 9:58:26 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by RogueZero
Could you guys explain these new commands (I dont know any of these commands ive never seen them before)and what the source code is doing? Cause im kind of a real newb. Thanks.


Sure, it''s nothing magic. The "switch" statement is simply a built-in identifier that allows you to pass in variable, and then choose multiple cases based on that variable. Here I passed in the "men" variable (for menu option), and then below, based on the value of the "men" variable we execute the proper function. If the user choses a "1", then the numbers are multiplied, if the user chooses a "2" then nothing happens but some text, but you could replace that with an addition function if you wanted.

Share this post


Link to post
Share on other sites
Alright guys youve been a great help so far but now im stuck this is what ive got as the program:

#include <iostream>
int multiply (int x, int y)
{
cout << " Multiplied " << x << " and " << y << "\n";
return (x*y);
}
int add (int x, int y)
{
cout << " Added " << x << " and " << y << "\n";
return (x+y);
}
int subtract (int x, int y)
{
cout << " Subtracted " << x << " and " << y << "\n";
return (x-y);
}
int divide (int x, int y)
{
cout << " Divided " << x << " and " << y << "\n";
return (x/y);
{
int main();
{
int a, b, c, d;
cout << " What math fuction do you wish to perform?\n";
cout << " 1. Multiply\n ";
cout << " 2. Divide\n ";
cout << " 3. Add\n ";
cout << " 4. Subtract\n";
cin >> d;
if(d = 1) { c = multiply(a, b); };
if(d = 2) { c = divide(a, b); };
if(d = 3) { c = add(a, b); };
if(d = 4) { c = subtract(a, b); };
cout << " Enter 2 numbers:\n ";
cin >>a;
cin >>b;
cout << "Heres the answer: " << c;
cin >> c;
return 0;
}
// the error signals that its here


and the error its giving me is on line 42 and says there is a parse error at the end of input. Oh yeah and what do you guys think of my first program?

Share this post


Link to post
Share on other sites
That probably means that you have an opening brace ({) that is not followed by a closing brace. Looks like it is in the divide funtion:

int divide (int x, int y)
{
cout << " Divided " << x << " and " << y << "\n";
return (x/y);
{

Make that:

int divide (int x, int y)
{
cout << " Divided " << x << " and " << y << "\n";
return (x/y);
}

Notice the change on that last line. That brace needs to be closing, not opening.

Share this post


Link to post
Share on other sites
Provided that your snippet there is a copy/paste job, your problem is in the divide() function. You wrote it like this:


int divide (int x, int y)
{
...
{ // note that it's a second opening brace!


Just change the { to a } where I marked it and it should work.

Usually when you get an error like that, it means you have missed or misplaced a brace or semi-colon or something. Don't feel bad, it a really easy mistake to make and the error spewed out by the compiler is useless for telling what's really wrong.

EDIT: Dammit! Beaten by mere seconds!

-Auron

[edited by - Auron on July 27, 2003 11:09:44 PM]

Share this post


Link to post
Share on other sites
Ok guys thanks alot for your help so far. I''m learning so much from you. Now another question how can i make the program start back at the top so instead of exiting after im done with one problem i can do another one. Should i use a loop and how would i use it. Then after i get that done how could i make and exit command or something that would let me exit when im done?

Share this post


Link to post
Share on other sites

int main() {
...
//Loop forever (or until a 'break' statement)

while(true) {
cout << " What math fuction do you wish to perform?\n";
cout << " 1. Multiply\n ";
cout << " 2. Divide\n ";
cout << " 3. Add\n ";
cout << " 4. Subtract\n";
cout << " 5. Exit\n";
cin >> d;
if(d == 5) {
//Jump out of the loop.

break;
}
cout << " Enter 2 numbers:\n ";
cin >>a;
cin >>b;
if(d == 1) {
c = multiply(a, b);
}
else if(d == 2) {
c = divide(a, b);
}
else if(d == 3) {
c = add(a, b);
}
else if(d == 4) {
c = subtract(a, b);
}
else {
cout << "Hmmm, let's try that again.\n";
//Go back to the top of the loop

continue;
}
cout << "Heres the answer: " << c << "\n";
}
return 0;
}


*EDIT* Fixed an error.

[edited by - SysOp_1101 on July 28, 2003 1:35:46 AM]

Share this post


Link to post
Share on other sites
The way I would do it is move everything you have in main to another function and have main call that function. Then, at the end of the program, if the user decides to repeat it you can simply have your new function call itself and it will start over.

Something I noticed...

if(d = 1) { c = multiply(a, b); };

Ignoring the fact that d = 1 should be d == 1, why do you have a semicolon after the closing brace for the if statement? It isn''t needed and only serves to clutter up your code. If you like it it doesn''t hurt anything, but it just looks a little weird.

Share this post


Link to post
Share on other sites
What about error-handling code? We don''t want the program to go crazy when a non-integer is entered...

int main()
{
cin.exceptions(ios::failbit);
try
{
cout << "Enter two numbers: ";
// etc

}
catch (ios::failure& )
{
cout << "invalid input!" << endl;
cin.clear();
while (cin && cin.get() != ''\n'');
}

// (add stuff here if desired)

}

Share this post


Link to post
Share on other sites
Hmmm, ok, here's a basic overview:

'while(true)' - Sets up a loop that will never exit (since true is always == true).

'if(d == 5) {break;}' - Checks to see if the user entered a 5 and if so, it 'break's out of the while loop. A 'break' is only valid within a loop structure (such as a 'while' or 'for' block). It's purpose is to stop the loop and jump to the instruction immediately following the loop structure (in this case, 'return 0;').

'else if' - Prevents further comparison of a true value in an if/then block. In other words, if the program determines that d == 2, then it won't check to see if d is also equal to 3, or 4. If you just use a series of if statements without 'else if', even after the program determines that d == 2, it will still check to see if d == 3 or d == 4. Else if's help to speed up the program a bit.

'else' - If the input isn't equal to anything in the 'if' or 'else if' statements, then your program will automaticaly run whatever you put in your else statement (in this case we're catching any numbers that aren't 1 - 5).

'continue' - Only works inside of loops. Tells the loop to start over from the top. In this case if we get to the 'else' block it means we had the user input an invalid number, so we jump to the top of the loop and ask for their input again.

Beer Hunter means well, but I think he overlooked the fact that you are a beginner. He's absolutely correct that programs should have error trapping, but the subject (or at least hs approach) is a little overkill for what your level and what you're trying to do at the moment.

Hope that helped make it clearer (not fuzzier) for ya'. If not, just keep posting your questions.

[edited by - SysOp_1101 on July 27, 2003 12:22:42 AM]

[edited by - SysOp_1101 on July 28, 2003 1:37:47 AM]

Share this post


Link to post
Share on other sites
quote:
Original post by RogueZero
Ok guys thanks alot for your help so far. I''m learning so much from you. Now another question how can i make the program start back at the top so instead of exiting after im done with one problem i can do another one. Should i use a loop and how would i use it. Then after i get that done how could i make and exit command or something that would let me exit when im done?


Ok let me try to explain this as simple as possible, like you said before you use a loop so the action repeats over and over..then you make the loop stop either way you want in your case you probably want the user to enter a number for example -1

bool done =false;
int input;

while(!done)
{
cin>>input;
if(input == -1) done =true;
}

There I hope you get an idea but no one''s going to write a tutorial here so I recommend you search a little more online for them and combine them with whatever book(s) ur using.

Share this post


Link to post
Share on other sites
quote:
Original post by RogueZero
Raloth, SySop, and Beer Hunter you guys have lost me. Ive just been learning c++ for a couple of days could you explain what your talking about a little bit?


Should you use a loop?

I would, yes. Otherwise, your user would have no way of terminating your program.

How would you use it?

Sysop solved this for you in his snippet of code. The while(true) keeps looping unless the user tells your program that he would like to exit, by using input #5. When that happens, the if(d == 5) (break; ) jumps out of the loop and your program finishes.

BeerHunter spoke of error handling code, which is a pretty advanced topic that you dont want to concern yourself with right now. Check out Sysop's code and go from there

EDIT - REFER TO SYSOPS CODE I CANT GET THE DAMN TAG RIGHT!!!

[edited by - Noods on July 27, 2003 12:34:15 AM]

Share this post


Link to post
Share on other sites
This is slightly derivative, but good habits are best learnt when first starting, so you don''t have to unlearn the bad ones. Anyway, I strongly suggest using something like

if ( 5 == d ) { ... }

instead of

if ( d == 5 ) { ... }

so that if you ever for get the extra = , you get a compile-time error instead of a run-time error or unexpected behavior. Only applies to comparing variables to constants, but occurs often enough...

Share this post


Link to post
Share on other sites
here''s the type of main loop i''d use - because your code should READ like what is does.


// your setup code here


bool quitRequested = false;
// while the user has not requested to quit

while(!quitRequested)
{
// do your menu here

// and get the users input


// process the user''s choice ...

// if they select quit (5 in the previous examples), set

// quitRequested = true;

}

// your cleanup code here


Share this post


Link to post
Share on other sites
also, you are using

if(choice 1)
do thing 1
if(choice 2)
do thing 2
if(choice 3)
do thing 3

... this type of situation is exactly what the "else if" is for ... and also the switch statement ...

basically ... your if lines are testing each condition, and doing the one''s that match ..

here''s it rewritten with else ifs


if(choice 1)
do thing 1
else if(choice 2)
do thing 2
else if(choice 3)
do thing 3
else
tell the user you did not understand their choice


this is jut like your code ... with 2 differences ...

1 - it''s more efficient, because once the computer sees that it has matched a choice, it quits trying to match other choices as well (the else if mean ONLY check if the previous ifs have failed ...)

2 - the else case can catch every situation that you haven''t handled, all at once ... so say they can enter any letter or number ... and you only handle 4 choices ... using else, you can write ONE block of code to handle all wrong choices the same ... easy ... perhaps a message like:

cout << "Command: " << d << " is unknown, please try again" << endl;

Share this post


Link to post
Share on other sites
next recommendation ...

name your variables with things that MEAN something ... obvious ... to you ...

why is your input variable "d" ???

I''m sure you have some reason ... but wouldn''t something like:

"usersChoice", or "menuChoice", or "command" mean a little more to you?

the a and b names for the operands are pretty fine (although something like "operandA" and "operandB" or even "val1" "val2" would be ok too ...

the name c could really stand to be something like "result"

so basically, in the simplest form, I''d make your code more readable by making your variables something like:

int a, b, result, command;

which will really make obvious which lines of code do your math, which part they''re dealing with, and which lines have to do with your menu choices ...

Share this post


Link to post
Share on other sites
ok guys ive looked over and looked over my code but i cant find what i left out. It says there is a parse error at the end of input on the last line. Does anyone see any thing i missed? Here's the code:

#include <iostream>
int multiply (int x, int y)
{
cout << " Multiplied " << x << " and " << y << "\n";
return (x*y);
}
int add (int x, int y)
{
cout << " Added " << x << " and " << y << "\n";
return (x+y);
}
int subtract (int x, int y)
{
cout << " Subtracted " << x << " and " << y << "\n";
return (x-y);
}
int divide (int x, int y)
{
cout << " Divided " << x << " and " << y << "\n";
return (x/y);
}
int main()
{
int a, b, c, d;
while(true){
cout << " What math fuction do you wish to perform?\n ";
cout << " 1. Multiply\n ";
cout << " 2. Divide\n ";
cout << " 3. Add\n ";
cout << " 4. Subtract\n";
cout << " 5. Exit\n";
cin >> d;
if(d == 5) {
break;
}
cout << " Enter the 2 numbers you wish to calculate:\n ";
cin >>a;
cin >>b;
if(d == 1) { c = multiply(a, b); }
else if(d == 2) { c = divide(a, b); }
else if(d == 3) { c = add(a, b); }
else if(d == 4) { c = subtract(a, b); }
else {
cout << " Not a valid choice!\n";
continue;
}
cout << "Heres the answer: " << c;
cin >> c;
return 0;
}



[edited by - RogueZero on July 28, 2003 8:22:05 PM]

Share this post


Link to post
Share on other sites
Code indentation is a Good Thing™. I''ve added some tabs:

#include <iostream>
int multiply (int x, int y)
{
cout << " Multiplied " << x << " and " << y << "\n";
return (x*y);
}
int add (int x, int y)
{
cout << " Added " << x << " and " << y << "\n";
return (x+y);
}
int subtract (int x, int y)
{
cout << " Subtracted " << x << " and " << y << "\n";
return (x-y);
}
int divide (int x, int y)
{
cout << " Divided " << x << " and " << y << "\n";
return (x/y);
}
int main()
{
int a, b, c, d;
while(true){
cout << " What math fuction do you wish to perform?\n ";
cout << " 1. Multiply\n ";
cout << " 2. Divide\n ";
cout << " 3. Add\n ";
cout << " 4. Subtract\n";
cout << " 5. Exit\n";
cin >> d;
if(d == 5) {
break;
}
cout << " Enter the 2 numbers you wish to calculate:\n ";
cin >>a;
cin >>b;
if(d == 1) { c = multiply(a, b); }
else if(d == 2) { c = divide(a, b); }
else if(d == 3) { c = add(a, b); }
else if(d == 4) { c = subtract(a, b); }
else {
cout << " Not a valid choice!\n";
continue;
}
cout << "Heres the answer: " << c;
cin >> c;
return 0;
}
From this, it''s easier to see that there''s a missing closing brace. I think you want one just before the ''cin >> c;'' line.

Share this post


Link to post
Share on other sites