I need to build a simple integer caluclator that perform arthmetic functions of addition, subtraction, multiplication, modulus and disvision. The calculator contains an Accumulator that stores the current result. The Accumulator is also involved with each operation. Make sure that you define a class for this program.
Once started, the Accumulator is set to zero, and the operation to be performed is set to addition (+). The program then repeats the following steps:

Request and Accept a number
Apply the stored operation (Acc op= number)
Request and Accept the next operation
This process repeats until the equals sign (=) is entered as an operation. At this point, the Accumulator contents are displayed and the calculator is reset (Accumulator set to zero and operation to +).
The following characters are legal operations:

+, -, *, %, /, =, and !.

The ! is treated the same as =, but causes the program to terminate. Any other characters entered as operations should cause a brief error message and should be ignored. Division by zero errors cause a reset.
Sample run:


SuperCalculator at you service!
------
Input: 10
Operation: *
Input: 2
Operation +
Input: -5
Operation: =
Result: 15
------
Input: 12
Operation: /
Input: 0
**Division by zero - start over
------
Input: 12
Operation: >
**Invalid operation - ignored
Operation: /
Input: 5
Operation: =
Result: 2
------
Input: 10
Operation: %
Input: 6
Operation: *
Input: 3
Operation: !
Result: 12

------
SuperCalculator Off!

Now I have worked and worked on this and I can not get my calculator to work. Can you see the error of my ways. Please help me find my way to the solution?

#include "stdafx.h"
#include<iostream>
using std::cout; 
using std::cin;
using std::endl;

class SupCal
{
public:
	// function that displays welcome message
	void displayMessage()
	{
		cout << "Super Calculator At Your Service!" << endl;
	} // end function displayMessage
	void displaySignoff()
	{
		cout << "Super Calculator off" << endl;
	} //end funtion displaySignoff
}; // end class SupCal


int main()
{
	int acc = 0; // accumulator is set to zero
	int input; // number input

	char oper='+'; // operation is set to '+'

	SupCal mySupCal; // create a SupCal oject
	mySupCal.displayMessage(); // call object's displayMessage function
	

	while(oper!= '!')
		
			cout << "Enter Number: "; // Prompt user to enter number
			cin >> input; // accept number

	switch (oper)
	{
	case '+':
		acc += input; 
		break;

	case '-':
		acc -= input;
		break;

	case '*':
		acc*=input; 
		break;

	case '/':
		if(input==0)
			{
				cout << "Division by zero - start over\n" << endl;
				acc=0;
				oper='+';
		}
		else
			acc/=input; 
		break;

	case '%':
		if(input == 0)
		{
			cout << "Division by zero - start over\n" << endl;
			acc=0; 
			oper='+';
		}
		else
			acc %= input;
		break;

	default:
		acc+=input; 
		break;

	}
		
	while(1)
	{
		cout << "Operation: ";
		cin >> oper;
		
		if(oper!='+'&& oper!='-' && oper!='*'&& oper!='/'&& oper!='%'&& oper!='='&& oper!='!')
		{
			cout<<"\nInvalid Operation - ignored";
		}
		else
			break;
	}
	if(oper=='=' || oper=='!')
	{
		cout<<"Result: "<< acc << endl;
		acc=0;
		oper='+'; 
		
		if(oper=='!')
		{
			mySupCal.displaySignoff(); // call object's displayMessage function
		
		}
		
	}
		
return 0; 
} // end main

The programs never stops running.

Thanks,
M~

the reason your code is looping continuously is because of your first while loop

while(oper!= '!')

cout << "Enter Number: "; // Prompt user to enter number
cin >> input; // accept number

you should create a validation variable instead of using your oper variable

#include "stdafx.h"
#include<iostream>
using std::cout; 
using std::cin;
using std::endl;

class SupCal
{
public:
	// function that displays welcome message
	void displayMessage()
	{
		cout << "Super Calculator At Your Service!" << endl;
	} // end function displayMessage
	void displaySignoff()
	{
		cout << "Super Calculator off" << endl;
	} //end funtion displaySignoff
}; // end class SupCal


int main()
{
	int acc = 0; // accumulator is set to zero
	int input; // number input

	char oper='+'; // operation is set to '+'

	SupCal mySupCal; // create a SupCal oject
	mySupCal.displayMessage(); // call object's displayMessage function
	

		
			cout << "Enter Number: "; // Prompt user to enter number
			cin >> input; // accept number

	switch (oper)
	{
	case '+':
		acc += input; 
		break;

	case '-':
		acc -= input;
		break;

	case '*':
		acc*=input; 
		break;

	case '/':
		if(input==0)
			{
				cout << "Division by zero - start over\n" << endl;
				acc=0;
				oper='+';
		}
		else
			acc/=input; 
		break;

	case '%':
		if(input == 0)
		{
			cout << "Division by zero - start over\n" << endl;
			acc=0; 
			oper='+';
		}
		else
			acc %= input;
		break;

	default:
		acc+=input; 
		break;

	}
		
	while(1)
	{
		cout << "Operation: ";
		cin >> oper;
		
		if(oper!='+'&& oper!='-' && oper!='*'&& oper!='/'&& oper!='%'&& oper!='='&& oper!='!')
		{
			cout<<"\nInvalid Operation - ignored";
		}
		else
			cout << "Enter Number: "; // Prompt user to enter number
			cin >> input; // accept number
				}
	if(oper=='=' || oper=='!')
	{
		cout << "Result: " << acc << endl;
		acc=0;
		oper='+'; 
		
		if(oper=='!')
		{
			mySupCal.displaySignoff(); // call object's displayMessage function
		
		}
		
	}
		
return 0; 
} // end main

Now I can not it to display right. No results! What is wrong? Do I need a MAXIMUM? As you can probably tell I am very new to C++. I can use all the constructive advise possible.

Cheers,
M~

You need to look more closely at where your loop is. Your code:

input a number
test your operator (it was never entered)
    process the operator
start a loop
    input operator
    if operator is illegal 
            output error
    else  input number
end loop
...

You never test any operator and process the result except the one you didn't enter.
Once you start the loop you
1) never exit the loop
2) never process an operator or the numbers

Think about where your loop should really start, and what should cause it to exit.

Why are you including #include "stdafx.h" ?

I include #include "stdafx.h" as it is automatic with my comiler. Should I remove it?

M~

I don't think it will be the cause of any of your problems but it's not a standard library. I believe it is specific to Microsoft compilers and will not work on anything not from them.

Considering it offers no real benefit to your program, it seems to make sense to make your programs portable and remove it.

Thank you, I am so new to C++ I do not know what is important and what is "fluff". I value your input greatly!

Mary

I am just not understanding where and how I test the loop. I switch a few thinks about, but still the accumulaor does not calculate properly and termination eludes the program. The Super Calculator does not display sign off either!

Where am I going wrong???

Thanks for your patience in advance.
Mary

#include<iostream>
using std::cout; 
using std::cin;
using std::endl;

class SupCal
{
public:
	// function that displays welcome message
	void displayMessage()
	{
		cout << "Super Calculator At Your Service!\n\n" << endl;
	} // end function displayMessage
}; // end class SupCal


int main()
{
	int acc = 0; // accumulator is set to zero
	int input; // number input

	char oper='+'; // operation is set to '+'

	SupCal mySupCal; // create a SupCal oject
	mySupCal.displayMessage(); // call object's displayMessage function
	

		
			cout << "\nEnter Number: "; // Prompt user to enter number
			cin >> input; // accept number
			
			while(1)
			{
				cout << "\nOperation: ";
				cin >> oper;

				if(oper=='=')
				{
					cout << "Result: " << acc << endl;
					oper ='+'; acc=0 ;
					break;
					
				}

				if(oper!='+'&& oper!='-' && oper!='*'&& oper!='/'&& oper!='%'&& oper!='='&& oper!='!')
					{
						cout<<"\nInvalid Operation - ignored";
				}				
				
				if(oper=='!'||oper == '=')
				{
					cout << "Super Calculator Off!" << endl;
					
				}
				else
				{
					cout << "\nEnter Number: "; // Prompt user to enter number
					cin >> input; // accept number
				}
				switch(oper)
				{
				case '+':
					acc += input;
					break;

				case '-':
					acc -= input;
					break;
				
				case '*':
					acc *= input; 
					break;

				case '/':
					if(input==0)
					{
						cout << "Division by zero - start over\n" << endl;
						acc = 0;
						oper= '+';
					}

					else
						acc /= input; 
					break;
				
				case '%':
					if(input == 0)
					{
						cout << "Division by zero - start over\n" << endl;
						acc = 0; 
						oper = '+';
					}
					else
						acc %= input;
					break;

				default:
					acc += input; 
					break;
				}
			}
		
return 0; 
} // end main

The Super Calculator does not display sign off either!

if(oper=='=')
{
    cout << "Result: " << acc << endl;
    oper ='+'; acc=0 ;
    break;
}
[...more code....]

if(oper=='!'||oper == '=')
{
}

The second of statement will never be reached if you enter '=' because you break out of the while loop a few statements earlier.

The reason why the answers are wrong, is because you take in the numbers and operators in the wrong order.
Try takinng two numbers for example and an operator and just write on paper what your program does with these values and you'll discover the error very soon. Just go through the program step by step.

Niek

First thing -- please use better formatting. You have too much indentation and not enough whitespace in your code. Look at your post above. Notice how it's hard to follow?

If you are going to use a switch() statement, why are you using all those if statements? Use one or the other, no need to use both.

You are using while(1) for your loop. When will it exit? Put a condition that meets your exit criteria and you won't have to test for it using an if in the loop.

I am so confused now! I cleaned up the formatting, fixed the indenting, rid of some of the 'if' statements , is it better?

The program will not calculate at all so I really did something wrong. I am a bit thicke and this the 13th straight hour I have been working on this is getting to me.

Can you in great detail (so I can understand) tell me what direction I should go?

#include<iostream>
using std::cout; 
using std::cin;
using std::endl;

class SupCal
{
public:
	// function that displays welcome message
	void displayMessage()
	{
		cout << "Super Calculator At Your Service!\n\n" << endl;
	} // end function displayMessage
}; // end class SupCal


int main()
{
	int acc = 0; // accumulator 
	int input; // number input

	char oper = '+'; // operation is set to '+'

	SupCal mySupCal; // create a SupCal oject
	mySupCal.displayMessage(); // call object's displayMessage function

	while(1)
	{
		cout << "\n Enter Number: "; // Prompt user to enter number
		cin >> input; // accept number

		cout << "\n Operation: ";
		cin >> oper;	
	}
	if(oper == '=')
	{
		
		cout << "\nResult: " << acc  << endl;
	}
	
	switch(oper)
	{
	case '+':
		acc += input;
		break;

	case '-':
		acc =- input;
		break;

	case '*':
		acc *= input; 
		break;

	case '/':
		if(input==0)
		{
			cout << "Division by zero - start over\n" << endl;
			acc = 0;
			oper= '+';
		}
		else
			acc /= input; 
			break;

		case '%':
			if(input == 0)
			{
				cout << "Division by zero - start over\n" << endl;
			}
			
			else
			{
				acc %= input;
			}
			break;

		

		case '!':
			{
				cout << "Super Calulator Off" << endl;
			}
			break;

		default:
			{
				acc += input; 
			}
			break;

				}
				
return 0; 
} // end main

I am so confused now! I cleaned up the formatting, fixed the indenting, rid of some of the 'if' statements , is it better?

Much!! A couple problems but much better.

The program will not calculate at all so I really did something wrong. I am a bit thicke and this the 13th straight hour I have been working on this is getting to me.

Can you in great detail (so I can understand) tell me what direction I should go?

You ain't gonna like it. Here's the direction you need to go -- think! See I told you :icon_wink:

OK, so you moved your loop above the switch. When is the switch useful? After you've input all your numbers and operators? And since you have no way to exit the loop, how do you expect to get to your switch?

First, think about what the program is supposed to do. What has to happen for one equation? If there's a 'get another' something, there's a loop around that something. If there is a 'calculate another' something, there's a loop around that too. BUT -- do you need one loop, or two?

Use pen and paper and write an equation to calculate. Below that, write down the variables you've defined in your program. Now, verrrry slooooowly do the calculation, one small step at a time filling in values for each variable as you go. Think in terms of the ifs, the switch, and the loop. What operations do you do more than once? In what order?

But first thing's first -- take a 30 minute break get away from the computer. Have some ice cream. Watch a lame TV show. Then come back to it. 13 hours straight is too long.

LOL
You are right! I would of prefered a better solution thatn think!!

I know I want the 'loop" to stop looping when it sees "=', but I can not fiqure how to make that happen.

Also I was wondering if I should learn to const Acc = op.

Oh, gosh, my brain is starting to smoke!!!

Thanks - I will eat some ice cream now!

Thank you for your time and patience - all!

Cheers,
Mary

Edit:

Tried to offer help but realized I should have read your first post. I'll get back to this when I get a minute.

Thanks, I am still trying to get things going. I thought I was getting close when the "power" went off (Florida).

I am really really tired too!!

Cheers,
M~

First of all: your loop is wrong. You just keep looping to input numbers and operators, but you never do anything with it. Your while(1) loop should include your switch()

Next: acc =- input; this should be: acc -= input; . Can you see the difference? In the first case acc will always be the negative number of the input (so 3 becomes -3; 5 becomes -5 etc etc etc)

I know I want the 'loop" to stop looping when it sees "=', but I can not fiqure how to make that happen.

If you want to stop looping when it sees an '=' why do you do:

case '!':
{
        cout << "Super Calulator Off" << endl;
}
break;

?
Just remove these lines and then modify the 'if' before the switch to this:

if(oper == '=')
{
    cout << "\nResult: " << acc  << endl;
    break;
}

I've just added a 'break' to break out of the loop when the '=' is entered.

Now I'll try to explain the problem with the wrong output:

Say we want to know what 3-1 is:
- Your program takes in a number (3)
- takes in an operator (-)
- now your program does acc-=3 (= -3)
- takes in a second number (1, but it doesn't do anything with it (ever))
- takes in an operator (=)
- show results stored in acc (-3)

So what you need to do is take in the first number seperately. And store it in 'acc' as an initial value.
Taking all this into account, your (very slightly) changed code would look like this:

#include<iostream>
using std::cout; 
using std::cin;
using std::endl;

class SupCal
{
public:
    // function that displays welcome message
    void displayMessage()
    {
        cout << "Super Calculator At Your Service!\n\n" << endl;
    } // end function displayMessage
}; // end class SupCal


int main()
{
    int acc = 0; // accumulator 
    int input; // number input

    char oper = '+'; // operation is set to '+'

    SupCal mySupCal; // create a SupCal oject
    mySupCal.displayMessage(); // call object's displayMessage function

    cout << "\n Enter Number: "; // Prompt user to enter number
    cin >> acc; // accept number

    while(1)
    {

        cout << "\n Operation: ";
        cin >> oper;	

        if(oper == '=')
        {
            cout << "\nResult: " << acc  << endl;
            break;
        }

        
        cout << "\n Enter Number: "; // Prompt user to enter number
        cin >> input; // accept number

        switch(oper)
        {
        case '+':
            acc += input;
            break;

        case '-':
            acc -= input;
            break;

        case '*':
            acc *= input; 
            break;

        case '/':
            if(input==0)
            {
                cout << "Division by zero - start over\n" << endl;
                acc = 0;
                oper= '+';
            }
            else
                acc /= input; 
            break;

        case '%':
            if(input == 0)
            {
                cout << "Division by zero - start over\n" << endl;
            }

            else
            {
                acc %= input;
            }
            break;

        default:
            {
                acc += input; 
            }
            break;

        }
    }
    cin.ignore();
    cin.get();
    return 0; 
} // end main

As you can see, you were almost there... :) This code still isn't very good, but I thought that I should keep you're program as original as possible for explaining reasons. Why do you have a class to show just one line of code for example?

I've added a cin.get(); to keep te console open, when the program ends.

One thing you should do, is to check if given input is valid.

Niek

I repeat:

First, think about what the program is supposed to do. What has to happen for one equation? If there's a 'get another' something, there's a loop around that something. If there is a 'calculate another' something, there's a loop around that too. BUT -- do you need one loop, or two?

Use pen and paper and write an equation to calculate. Below that, write down the variables you've defined in your program. Now, verrrry slooooowly do the calculation, one small step at a time filling in values for each variable as you go. Think in terms of the ifs, the switch, and the loop. What operations do you do more than once? In what order?

So do an equation completely by hand, step by step, and write down each step. Then look at those steps carefully. Then write another and solve if by only following your steps -- this time without thinking. If you get the correct answer, convert your steps into code.

And thanks, niek_e. Maybe I should have just written it for him, too. Save you the trouble :icon_confused:

If you want to stop looping when it sees an '=' why do you do:

case '!':
{
        cout << "Super Calulator Off" << endl;
}
break;

Read his instructions, you'll see.

And thanks, niek_e. Maybe I should have just written it for him, too. Save you the trouble :icon_confused:

I've changed 4 lines of code. The rule is NOT TO GIVE AWAY HOMEWORK. She made 90% of the program herself. And I tried to explain what I changed and why I changed that.
I know that you don't like actually giving people code, but I thought that the rule was: Help people who SHOW EFFORT. 13 hours of work sound like effort to me

Guys,

Thank you all so much. Early this morning I was driving up the beach and had that ahhh! moment!

I fiqured I need to really think about the calculations s-l-o-w-e-r! Your advise WaltP! Then I saw the left - right issue. Your advise Neik! I need to do the correct order - Codeaa and all of your advise!

It is amazing what a little 6 hour sleep can do!

Oh the reason for the class was the assignment read tht I needed a class. After I get the basic structure built, I will break it into .cpp .h and main files.

I did the first function "displayMessage" to show "Super Calculator At Your Service". I really wanted to learn how to do a function so tht is why it is in before the others. I will be creating add, sub, multiply, divide and factor functions.

Again I thank you so much!

I will complete this program and I will show you that your advise, instruct and knowledge taught me. I learned more from all you, then I learned in my class so far.

And WaltP, I will remeber to code with mega amounts of whitespace!!!

Off to code now,

Cheers,
Mary

And WaltP, I will remeber to code with mega amounts of whitespace!!!

Please don't! Use appropriate amounts. The following is just as bad as none :icon_wink:

if   ( a  ==      b)
{
                      j    =      alpha      *      89;
                      cout        <<        "Answer #1"           <<
                                               j   <<            endl;
             }

:icon_twisted:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.