Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
#ifndef CALC_H
#define CALC_H
class calc
{
double numb1;
double numb2;
public:
calc();
void FUN_SUM();
void FUN_Subtraction();
void FUN_Multiplication();
void FUN_Division();
void FUN_Power();
void FUN_Squareroot();
void FUN_Switch();
void FUN_Loob();
};
#endif // CALC_H
#include "calc.h"
#include <iostream>
#include <cmath>
using namespace std;
calc::calc()
{
numb1 = 0;
numb2 = 0;
}
void calc::FUN_SUM()
{
cout << "Enter number 1 " << endl;
cin >> numb1;
cout << "Enter number 2 " << endl;
cin >> numb2;
double Result_Of_Sum;
Result_Of_Sum = numb1+numb2;
cout << "The result of Sum = " << Result_Of_Sum << endl;
}
void calc::FUN_Subtraction()
{
cout << "Enter number 1 " << endl;
cin >> numb1;
cout << "Enter number 2 " << endl;
cin >> numb2;
double Result_Of_Subtraction;
Result_Of_Subtraction = numb1 - numb2;
cout << "The result of Subtraction = " << Result_Of_Subtraction << endl;
}
void calc::FUN_Multiplication()
{
cout << "Enter number 1 " << endl;
cin >> numb1;
cout << "Enter number 2 " << endl;
cin >> numb2;
double Result_Of_Multiplication;
Result_Of_Multiplication = numb1*numb2;
cout << "The result of Multiplication = " << Result_Of_Multiplication << endl;
}
void calc::FUN_Division()
{
cout << "Enter number 1 " << endl;
cin >> numb1;
cout << "Enter number 2 " << endl;
cin >> numb2;
double Result_Of_Division ;
Result_Of_Division = numb1/numb2;
cout << "The result of Division = " << Result_Of_Division << endl;
}
void calc::FUN_Power()
{
cout << "Enter number 1 " << endl;
cin >> numb1;
cout << "Enter number 2 " << endl;
cin >> numb2;
double Result_Of_Power;
Result_Of_Power = pow(numb1,numb2);
cout << "The result of Power = " << Result_Of_Power << endl;
}
void calc::FUN_Squareroot()
{
cout << "Enter the tow number you want Square root \n";
cin >> numb1;
double Result_Of_Square_root;
Result_Of_Square_root = sqrt(numb1);
cout << "The result of Square root = " << Result_Of_Square_root << endl;
}
void calc::FUN_Switch()
{
int S;
cout << "Enter the number you operator do you want do it " << endl;
cout << "1- Addition" << endl;
cout << "2- Subtraction" << endl;
cout << "3- Multiplication" << endl;
cout << "4- Division" << endl;
cout << "5- Power" << endl;
cout << "6- Square Root" << endl;
cout << "7- Exit" << endl;
cin >> S;
switch (S)
{
case 1:
FUN_SUM();
break;
case 2:
FUN_Subtraction();
break;
case 3:
FUN_Multiplication();
break;
case 4:
FUN_Division();
break;
case 5:
FUN_Power();
break;
case 6:
FUN_Squareroot();
break;
default :
break;
}
}
void calc::FUN_Loob()
{
char L;
do
{
FUN_Switch();
cout << "Do you want do another operator ( 'y' or 'n'?) \n";
cin >> L;
if (L== 'y' || L=='Y' || L=='n' || L=='N')
continue;
else
cout << "you are enter roang later\n";
}
while (L == 'Y' || L == 'y' );
}
#include <iostream>
#include "calc.h"
using namespace std;
int main()
{
cout << "Welcome to my simple Calculator\n";
calc simple_calc;
simple_calc.FUN_Loob();
cout << "\n Tank you for use my App :) :) " << endl;
return 0;
}
my question is how i can enable user Calc any value with operators like regular Calculator
for example 1+9*8-1+5 i want my program do like that but i don`t know how ?? :( :(
Writing a calculator is not an easy task, as there is more involved:
Operator Precedence
Grouping
Evaluating of expressions
Operator Precedence
Operator precedence is the grouping of operations, such as performing all multiplication and division before addition and subtraction. A calculator program should handle precedence without parenthesis (grouping).
Grouping
A more advanced calculator will allow grouping of expressions, using parenthesis. The calculator should be able to evaluate the inner most expression and work outward.
Evaluating of Expressions
This means allowing more than 1 digit numbers, and whitespace between numbers and symbols. Also, once the expression is parsed, it needs to be evaluated. The calculator should call the appropriate functions based on the operation (specified by the User).
I suggest you allow the User to enter an expression, and your program read it in as a string. Your program will then parse the string, then evaluate the expression(s).
Search the web and StackOverflow for "c++ calculator" for examples.
Related
I am trying to build a calculator in C++. I'm new to the program and have to do this for a school assignment, so sorry for my ignorance. English is also my second language so excuse me if I don't make much sense.
Let's say I have two integers A and B for which a user has to assign a value to either add, subtract, etc. How would I then be able add a third integer (let's say X) without all three showing up when I run the program? So instead of having to type a value for A, B, AND X, it only asks to type a value for X?
For example 4 + 5 = 9, but the calculator can also square numbers, so how do I get the option of a user just filling in 4 squared = 16, while still keeping the former code that lets me add and subtract two numbers?
Maybe seeing the code would help understand what I mean? Sorry if I'm confusing.
#include <iostream.h>
#include <conio.h>
int main ()
{
cout << "Calculator [v.1.0]" << endl;
cout << "(c) 2021 <Chayenne van der Erf>" << endl << endl;
cout << "Kies een bewerking en druk op Enter:" << endl;
cout << "1. Optellen 2. Aftrekken" << endl;
cout << "3. Vermenigvuldigen 4. Delen" <<endl;
cout << "5. Kwadraat 6. Worteltrekken" <<endl;
cout << "7. Reciproke 8. Logarithme" <<endl;
cout << "0. Exit" << endl << endl;
int Bewerking;
cout << "Bewerking: ";
cin >> Bewerking;
cout << "" << endl;
switch (Bewerking) {
case 1:
cout << "+";
break;
case 2:
cout << "-";
break;
case 3:
cout << "*";
break;
case 4:
cout << "/";
break;
default: "Invalid Number";
}
cout << "" << endl << endl;
double A, B;
cout << "Enter een waarde: ";
cin >> A;
cout << "Enter een waarde: ";
cin >> B;
int antwoord;
if (Bewerking == 1) {antwoord = A + B;}
else if (Bewerking == 2 ) {antwoord = A - B;}
else if (Bewerking == 3) {antwoord = A * B;}
else if (Bewerking == 4) {antwoord = A / B;}
cout << "" << endl;
cout << "= " << antwoord << endl;
getch();
return 0;
}
Make the variables, and the reading, conditional on the operation.
Example outline:
if (operation takes one input)
{
double x;
cin >> x;
Calculate result...
}
else if (operation takes two inputs)
{
double x, y;
cin >> x >> y;
Calculate result...
}
else if (operation takes three inputs)
{
double x, y, z;
cin >> x >> y >> z;
Calculate result...
}
Print result...
The user is asked if s/he wants to return to main menu, if the user inputs n/N it only proceeds to the next solution when it should immediately end the program. Shown below is the code I used for the program. Please help me to make solution on how to end the program immediately when No is chosen as his/her choice. Thank you so much!
void number()
int b=0;
int groupChoice=0;
float ave[groupChoice];
int trials[groupChoice];
float result,sumRes,dAve;
int sumTry=0;
char choice;
cout << "\nNUMBER OF TRIALS" << endl;
cout << "\nHow many groups? ";
cin >> groupChoice;
for (int j=0;j<groupChoice;j++)
{
cout << "Average distance for group " << j+1 << ": ";
cin >> ave[j];
cout << "No. of trials for group " << j+1 << ": ";
cin >> trials[j];
}
cout << "\nGroups\t\tAve. Distance(x)\tNo. of trials(w)\tx(w)" << endl;
for (int i=0;i<groupChoice;i++)
{
result=ave[i]*trials[i];
cout << "Group " << i + 1 << "\t\t" << ave[i] << "\t\t\t" << trials[i] << "\t\t\t" << result << endl;
sumTry=sumTry+trials[i];
sumRes+=result;
}
cout << "\t\t\t\t\tSum = " << sumTry << "\t\tSum = " << sumRes << endl;
dAve = sumRes / sumTry;
cout << "Distance Average is " << dAve << endl << endl;
b=0;
while(b==0)
{
cout << "Would you like to return to main menu? [Y or N]: ";
cin >> choice;
if (choice=='Y'||choice=='y')
{
b++;
system("cls");
a=0;
main();
}
else if (choice=='N'||choice=='n')
{
b++;
break;
}
}
You can terminate your program with
void std::exit( int exit_code );
eg
std::exit(EXIT_SUCCESS);
https://en.cppreference.com/w/cpp/utility/program/exit
There are two options
use
std::exit(<exit_code>); or
std::_Exit(<exit_code>);
more info:
https://en.cppreference.com/w/c/program/_Exit
I am a very newbie programmer, so I don't really know much about writing code to protect the application.. Basically, I created a basicMath.h file and created a do while loop to make a very basic console calculator (only two floats are passed through the functions). I use a series of if and else if statements to determine what the users wants to do. (1.add, 2.subtract, 3.multiply, 4.divide) I used a else { cout << "invalid input" << endl;} to protect against any other values, but then I tried to actually write a letter, and the program entered a infinite loop. Is there anyway to protect against users who accidentally hit a character instead of a number?
`#include <iostream>
#include "basicMath.h"
using namespace std;
char tryAgain = 'y';
float numOne = 0, numTwo = 0;
int options = 0;
int main()
{
cout << "welcome to my calculator program." << endl;
cout << "This will be a basic calculator." << endl;
do{
cout << "What would you like to do?" << endl;
cout << "1. Addition." << endl;
cout << "2. Subtraction." << endl;
cout << "3. Multiplication" << endl;
cout << "4. Division." << endl;
cin >> options;
if (options == 1){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " + " << numTwo << " = " << add(numOne, numTwo) << endl;
}
else if (options == 2){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " - " << numTwo << " = " << subtract(numOne, numTwo) << endl;
}
else if (options == 3){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " * " << numTwo << " = " << multiply(numOne, numTwo) << endl;
}
else if (options == 4){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " / " << numTwo << " = " << divide(numOne, numTwo) << endl;
}
else {
cout << "Error, invalid option input." << endl;
}
cout << "Would you like to use this calculator again? (y/n)" << endl;
cin >> tryAgain;
}while (tryAgain == 'y');
cout << "Thank you for using my basic calculator!" << endl;
return 0;
}
`
One way would be to use exception handling, but as a newbie you're probably far from learning that.
Instead use the cin.fail() which returns 1 after a bad or unexpected input. Note that you need to clear the "bad" status using cin.clear().
A simple way would be to implement a function:
int GetNumber ()
{
int n;
cin >> n;
while (cin.fail())
{
cin.clear();
cin.ignore();
cout << "Not a valid number. Please reenter: ";
cin >> n;
}
return n;
}
Now in your main function wherever you are taking input, just call GetNumber and store the returned value in your variable. For example, instead of cin >> numOne;, do numOne = GetNumber();
When you input to cin, it is expecting a specific type, such as an integer. If it receives something that it does not expect, such as a letter, it sets a bad flag.
You can usually catch that by looking for fail, and if you find it, flush your input as well as the bad bit (using clear), and try again.
Read a whole line of text first, then convert the line of text to a number and handle any errors in the string-to-number conversion.
Reading a whole line of text from std::cin is done with the std::getline function (not to be confused with the stream's member function):
std::string line;
std::getline(std::cin, line);
if (!std::cin) {
// some catastrophic failure
}
String-to-number conversion is done with std::istringstream (pre-C++11) or with std::stoi (C++11). Here is the pre-C++11 version:
std::istringstream is(line);
int number = 0;
is >> number;
if (!is) {
// line is not a number, e.g. "abc" or "abc123", or the number is too big
// to fit in an int, e.g. "11111111111111111111111111111111111"
} else if (!is.eof()) {
// line is a number, but ends with a non-number, e.g. "123abc",
// whether that's an error depends on your requirements
} else {
// number is OK
}
And here the C++11 version:
try {
std::cout << std::stoi(line) << "\n";
} catch (std::exception const &exc) {
// line is not a number, e.g. "abc" or "abc123", or the number is too big
// to fit in an int, e.g. "11111111111111111111111111111111111"
std::cout << exc.what() << "\n";
}
I am programming a simple calculator that subtracts adds divides or multiplies depending on whether you type 1 2 3 or 4. I keep getting this error. Keep in mind I am newer to C++. It happens with the IF lines in Mode == 3 and Mode == 4
#include <iostream>
int main(){
using namespace std;
int x;
int y;
int x2;
int y2;
int x3;
int y3;
int x4;
int y4;
int Mode;
cout << "Welcome to Brian's Calculator!";
cout << endl;
cout << "Pick a mode. 1 is Addition. 2 Is Subtraction. 3 is Multiplacation. 4 is Division";
cin >> Mode;
if (Mode==1){
cout << "You chose addition.";
cout << endl;
cout << "Pick a number.";
cout << endl;
cin >> x;
cout << endl;
cout << "Pick another.";
cout << endl;
cin >> y;
cout << "The sum of the numbers you chose are: " << x+y <<".";
return 0;
};
if (Mode==2){
cout << "You chose subtraction.";
cout << endl;
cout << "Pick a number.";
cout << endl;
cin >> x2;
cout << endl;
cout << "Pick another.";
cout << endl;
cin >> y2;
cout << "The difference of the numbers you chose are: " << x2-y2 <<".";}
return 0;
};
if (Mode==3){
cout << "You chose Multiplacation.";
cout << endl;
cout << "Pick a number.";
cout << endl;
cin >> x3;
cout << endl;
cout << "Pick another.";
cout << endl;
cin >> y3;
cout << "The product of the numbers you chose are: " << x3*y3 <<".";
return 0;
};
if (Mode==4){
cout << "You chose Division.";
cout << endl;
cout << "Pick a number.";
cout << endl;
cin >> x4;
cout << endl;
cout << "Pick another.";
cout << endl;
cin >> y4;
cout << "The quotient of the numbers you chose are: " << x4/y4 <<".";
return 0;
};
At this line:
cout << "The difference of the numbers you chose are: " << x2-y2 <<".";}
You have an extra }
PROBLEM: you have two end-braces instead of one:
if (Mode==2){
...
// DELETE THE EXTRANEOUS "}"!
cout << "The difference of the numbers you chose are: " << x2-y2 <<".";}
return 0;
};
SUGGESTED ALTERNATIVE:
if (Mode==2){
...
// DELETE THE EXTRANEOUS "}"!
cout << "The difference of the numbers you chose are: " << x2-y2 <<".";
return 0;
}
EVEN BETTER:
switch (Mode) {
case 1 :
...
break;
case 2 :
...
break;
On this line you have a misplaced }:
cout << "The difference of the numbers you chose are: " << x2-y2 <<".";}
^
when you fix that you will need an extra } after the end of your program to close main as well. Also you do not need a ; after the } when you close the if statements for example:
if (Mode==1){
// code...
};
^
Could someone explain why pow() in the following code is returning a 0 when the program is run, rather than the actual calculation? I'm a newbie to programming and I'm entirely stumped.
Thanks for any help.
#include <iostream>
#include <math.h>
#include <windows.h>
using namespace std;
//Prototypes:
double phiExpo;
double phiNegExpo;
double opt1f(double phi, double userInput){
return userInput * phi;}
double opt2f(double phi, double userInput){
return userInput / phi;}
double opt3f(){
return phiExpo;}
double opt4f(){
return phiNegExpo;}
double phiExpof(double phi, double userInput){
pow(phi, userInput);}
double phiNegExpof(double phi, double userInput){
pow(phi,-userInput);}
//Execute program:
int main()
{
double userInput;
int userChoice;
double phi = 1.61803399;
bool quit = false;
int userChoice2;
cout << "I want to (press corresponding number, then enter):" << endl;
cout << endl;
startchoices:
cout << "1. Multiply by phi:" << endl;
cout << "2. Divide by phi:" << endl;
cout << "3. Exponentiate phi:" << endl;
cout << "4. Negatively exponentiate phi:" << endl;
cout << "5. Quit." << endl;
cout << endl;
cin >> userChoice;
cout << endl;
do {
switch (userChoice){
case 1:
cout << "Enter number for multiplication: ";
cin >> userInput;
cout << endl;
cout << "Phi multiplied by " << userInput << ": ";
cout << opt1f(phi, userInput) << endl;
cout << endl;
Sleep(2000);
cout << "1. Continue." << endl;
cout << "2. Return to menu." << endl;
cout << endl;
cin >> userChoice2;
cout << endl;
if(userChoice2 > 1){
goto startchoices;}
break;
case 2:
cout << "Enter number for division: ";
cin >> userInput;
cout << endl;
cout << "Phi divided by " << userInput << ": ";
cout << opt2f(phi, userInput);
cout << endl;
Sleep(2000);
cout << "1. Continue." << endl;
cout << "2. Return to menu." << endl;
cout << endl;
cin >> userChoice2;
cout << endl;
if(userChoice2 > 1){goto startchoices;}
break;
case 3:
cout << "Enter number to exponentiate phi by: ";
cin >> userInput;
cout << endl;
cout << "Phi to the power of " << userInput << ": ";
cout << opt3f();
cout << endl;
Sleep(2000);
cout<<endl;
cout << "1. Continue." << endl;
cout << "2. Return to menu." << endl;
cout << endl;
cin >> userChoice2;
cout << endl;
if(userChoice2 > 1){goto startchoices;}
break;
}
}
}
You never actuall call pow. On choice 3, you only call opt3f, which only returns the global variable phiExpo, which is initialized to 0 because it's global. Then you also need to return from the phiExpof function, like others already pointed out.
It is probably not returning 0. Instead, you are not returning the result of pow:
double phiExpof(double phi, double userInput){
return pow(phi, userInput);
}
When you don't explicitly return a value, you will get undefined behavior, in this case 0.
Note:
I didn't notice the other code... This is one problem. The other is that you aren't actually calling phiExpof. Instead you are returning phiExpo which is a global variable.
How do you know it's returning 0? Your code doesn't even check the return value.