I want to use C++ to make a calculator, so that I can enter an expression and calculate the result.
For example,
input
(5.2+4)*ln3.4+sin3
output
11.39985
The problem is that I don't know how to separate the number and the operator from the string. For the length of the operands and numbers are different.
Is there any good way?
That's actually a much harder problem than it seems at first, and I say that from experience.
If you want an example of how to do it completely from scratch, here is a question where I posted an example I was working on. It is certainly not complete, but links to a great Java article (actually, probably the best article) on Pratt parses, which in my opinion is the best way to parse expressions. My question was on my attempt to port the Java code found there to C++. You can see a problem I ran into there.
You will also need to know some theory on lexers, and learn how to create tokens, which I don't ask about there.
The point is, you have a lot of research ahead of you, if you want to start from scratch, or even if you want to just know the theory of what's going on, but I certainly encourage you to try it if you don't have a deadline for it.
Use a library such as exprtk.
I'm going to assume that you're a total noob which leads me to advise you to always Google for a library that solves your problem.
I programmed the calculator using function ,loops, switch case.
it can also be programmed with using if else statement but then it will be a simple one. I had made it like a real calculator it can take unlimited argument, while the other takes only 2 numbers as argument.
#include <iostream>
#include <conio.h>
using namespace std;
int add()
{
int total, a, sum = 0;
cout << "how much number you want to calculate :";
cin >> total;
for (int i = 1; i <= total; i++)
{
cout << "enter number " << i << "for +" << endl;
cin >> a;
sum = sum + a;
}
cout << "total addition is:" << sum;
return 0;
}
int subtract()
{
int sub = 0, a, b[20], total;
cout << "how much number you want to calculate :";
cin >> total;
cout << "enter number 1 for - : \n";
cin >> a;
a = -a;
for (int i = 1; i < total; i++)
{
cout << "enter number " << i << "for - :" << endl;
cin >> b[i];
sub = sub - a - b[i];
a = 0;
}
cout << "HENCE THE SUBTRACT IS :" << sub;
}
int divide()
{
float h;
float a;
float b;
cout << "enter number 1 : ";
cin >> a;
cout << "enter number 2 : ";
cin >> b;
h = a / b;
cout << "division is :" << h;
}
int multiply()
{
int a[20];
int total, multi = 1;
cout << "how much number you want to multiply\n";
cin >> total;
for (int i = 0; i < total; i++)
{
cout << "enter number to multiply\n";
cin >> a[i];
multi = multi * a[i];
}
cout << "multiplicaion is : " << multi;
}
int main()
{
int num1[20], num2[20];
char sign;
cout << "chouse a sign"
"\npress this for executing the action +"
"\npress this for executing the action -"
"\npress this for executing the action X"
"\npress this for executing the action /\n";
cin >> sign;
switch (sign)
{
case '+':
add();
break;
case '-':
subtract();
break;
case '*':
multiply();
break;
case '/':
divide();
break;
default:
cout << "chouse something";
break;
}
return 0;
}
Related
Consider the following code:
#include <iostream>
using namespace std;
int main(){
int a,b;
cout << "Enter two positive numbers:" <<endl;
cin >> a >> b;
if (a<b) cout <<a<<" is less than "<< b<<endl;
else if (a>b) cout <<a<<" is greater than " <<b<<endl;
}
How can I make the program endlessly repeat asking for a new set of numbers as input?
Here's the simplest way of doing what you want (there are other ways). Basically, you just need to 'wrap' the code that you want to repeat in a loop, where the 'test' condition for the loop will always evaluate to true.
Note the comments with "///" I've given:
#include <iostream>
//using namespace std; /// Search this site for "Why using namespace std is bad"
using std::cout;/// Just declare usage of those feature you ACTUALLY use...
using std::cin;
using std::endl;
int main() {
int a, b;
while (true) { /// The test condition will always be "TRUE" so the loop will never end!
cout << "Enter two positive numbers:" << endl;
cin >> a >> b;
if (a < b) cout << a << " is less than " << b << endl;
else if (a > b) cout << a << " is greater than " << b << endl;
// cout /// This line is wrong!
}
}
Feel free to ask for further clarification and/or explanation.
Depends on what exactly do you want your program to do. If you want it to "deny access". For example lets say you have want a number K > 3 always for the program to continue. The all you have to do is use a do- while loop:
do
{
cout << "Enter the value for the sequence: ";
cin >> K;
if ( K <= 3)
{
cout << "Write a bigger number!" << endl;
}
} while(K <= 3);
Otherwise just use a normal loop with the condition suitable for the task.
Suppose your program is to find the Factorial of number and you want it to loop such that it ask for new value from the user
int main()
{
int n;
while (true) {
int factorial = 1;
cin >> n;
if (n==0) {
cout << 0;
}
else {
for (int i=n;i>0;i--) {
factorial = factorial*i;
}
cout << factorial;
}
}
return 0;
}
I am a rookie coder here and I can't seem to figure out what to add to my code here to get it right. It is supposed to ask the user again if they do not answer the question "Do you want to make another calculation Y or N?" correctly. I want it to repetitively ask the user to enter y or n if they enter something else. I feel like it is obvious I am just missing it. This is for school, to be clear.
I've tried nesting a do while loop and an if statement but only to get run time errors
#include <iostream>
using namespace std;
int main() {
int base, exponent;
long int result = 1;
char choice;
int i;
do
{
cout << "This program raises a number to a specific power." << endl;
cout << "\nEnter a base integer greater than 1: ";
cin >> base;
cout << "\nEnter an exponent integer to raise that number to: ";
cin >> exponent;
for (i = 1; i <= exponent; i++)
{
result = result * base;
}
cout << "\n" << base << " to the power of " << exponent << " = " << result << endl;
result = 1;
// ***** HERE IS WHERE I NEED HELP, WHAT TO
// DO IF THEY DONT ENTER Y OR N.....
cout << "\nWould you like to make another calculation? Y or N: ";
cin >> choice;
cout << endl;
}
while (choice == 'y' || choice == 'Y');
cout << "Good bye, then. Have a good day.\n" << endl;
return 0;
}
When I tried adding a nested do while loop, and entered a character answer other than y or n, it would go to a part of the program it should not have.
*this is my first question so I hope I've done this correctly
You can use another do-while loop to wrap the input section.
do
{
cout << "This program raises a number to a specific power." << endl;
cout << "\nEnter a base integer greater than 1: ";
cin >> base;
cout << "\nEnter an exponent integer to raise that number to: ";
cin >> exponent;
for (i = 1; i <= exponent; i++)
{
result = result * base;
}
cout << "\n" << base << " to the power of " << exponent << " = " << result << endl;
result = 1;
do
{
cout << "\nWould you like to make another calculation? Y or N: ";
cin >> choice;
cout << endl;
} while (choice != 'y' && choice != 'Y' && choice != 'n' && choice != 'N');
}
while (choice == 'y' || choice == 'Y');
Learn to think organically here. Let me do a procedural approach.
We begin by bringing your formulations into a more technical form, until it is syntactically and semantically working. Let's start by transforming it into this:
void process_things()
{
...
while(still_require_answer)
{
ask_for_answer();
}
...
}
This is very close to how you formulate it verbally, yes? Now, let's flesh it out.
string ask_for_answer(bool& still_require_answer);
void process_things()
{
...
string answer = "";
bool still_require_answer = true;
while(still_require_answer)
{
answer = ask_for_answer(still_require_answer);
}
...
}
// hope you understand the concept of a reference here,
// that is what the ampersand (&) does, if not, ask
string ask_for_answer(bool& still_require_answer)
{
string answer = ""; // always initialize
cout << "State answer: ";
cin >> answer;
cout << endl;
if(answer == "Y" or ...)
{
still_require_answer = false;
}
return answer;
}
Hope this helps you. In the long run, you might want to go OOP and use classes here. The code here is a little bit verbose, but orderly.
Note that I have put the routine in a new function process_things. Anything that is more than a few lines which you can name you should think about making a function (or a class method). Your main should be quite small. Cutting things down into smaller units helps you keeping thisng orderly and makes the design of each single unit easy (divide-and-conquer) and allows you to quicker locate problems as you can test every function separately (later, this leads to automated unit tests).
One could also take the while and put it into it's own function string ask_until_valid_answer();, and if we do that, dissolve ask_for_answer and put it's content there. What I want to focus on is to have it organically, that is use self-descriptive names which explain the program while reading it, and to cut the program into understandable units. Here would be this other layout:
string ask_until_valid_answer();
void process_things()
{
...
string answer = ask_until_valid_answer();
...
}
string ask_until_valid_answer()
{
string answer = "";
bool still_require_answer = true;
while(still_require_answer)
{
cout << "State answer: ";
cin >> answer;
cout << endl;
if(answer == "Y" or ...)
{
still_require_answer = false;
}
}
return answer;
}
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int numofEmployees();
int daysMissed(int);
int AverageMissed(int, int);
int main()
{
cout << "Welcome to employee absentee calculator!" << endl;
int numEmployees = numofEmployees();
int Missed = daysMissed(numEmployees);
double misAverage = AverageMissed(numEmployees, Missed);
cout << "There are " << numEmployees << " in the company. They have missed " << Missed << " days total. On average, they have missed " << misAverage << " days." << endl;
return 0;
}
int numofEmployees() {
cout << "How many employees are in your company? ";
int employees;
cin >> employees;
while (employees < 1) {
cout << "Employee count must 1 or greater!" << endl;
}
return employees;
}
int daysMissed(int numEmployees) {
int Absence, totAbsence = 0;
for (int i = numEmployees; i < numEmployees; i++) {
cout << "How many days has each employee missed this passed year? ";
cin >> Absence;
totAbsence += Absence;
}
while (Absence < 0) {
cout << "Values entered must be positive numbers!" << endl;
cin >> Absence;
}
return totAbsence;
}
int AverageMissed(int numEmployees, int Missed){
double Average;
Average = double(numEmployees) / double(Missed);
return Average;
}
This code is being used to calculate the average number of employee absences by way of using three functions. The second function is not working correctly as it is not being called properly by the main. This is for a school assignment.
The problem is daysMissed - if numEmployees is <= 0, then Absense will be uninitialized. But, you say, "I check that in numofEmployees" - the problem is that the compiler doesn't do that sort of whole-program analysis before issuing these warnings.
There is another problem: daysMissed is wrong (twice). If there are two employees, and I enter -2 and 1, there will be no error for the negative number. If on the other hand, if I enter 1 and -2, you never correct totAbsence. You would be much better off writing a little function which reads a number >= some limit in a loop, and keeps prompting until given the correct value. Something like:
int read(const char* prompt, const char* err_prompt, int limit) {
cout << prompt << endl;
for(;;) {
int result;
cin >> result;
if (result >= limit) {
return result;
}
cout << err_prompt << endl;
}
}
Then daysMissed becomes much pleasanter to write - and you can use the same function to read the number of employees (which will go into an infinite loop at the moment)
You should also validate a division by zero plus change the return type.
double AverageMissed(int numEmployees, int Missed){
if (Missed > 0) return double(numEmployees) / Missed;
return 0;
}
by the way, there is no need to cast both operands in the division (/). Casting one of them will be enough to return a double type.
I tried to implement the do..while loop in a simple program. In the program, I ask for a payroll amount, then calculate the sum of the payroll and outputs the sum and the number of valid entries. That's too simple so I decided to add some error checking.
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
const int SENTINEL = -1;
int main(){
int payroll, payroll_sum, counter = 0;
do{
cout << "Enter a payroll amount (-1 to end): ";
cin >> payroll;
if((payroll < SENTINEL)){
cout << "\nError!\nPlease enter a correct value.\n" << endl;
int main(payroll);
}
else{
payroll_sum += payroll;
counter += 1;
cout << "\n";
}
if(payroll == SENTINEL){
payroll_sum += 1;
counter -= 1;
}
}while(payroll != SENTINEL);
cout << "\n\nTotal payroll amount is: " << payroll_sum;
cout << "\nTotal number of entries is: " << counter;
return 0;
}
The code works, but it bugs me that I have to deduct one from the counter and add one to the sum because I don't know how to make the program ignore the SENTINEL input. And, I'm sure that there's a better way to do the error handling. Thanks in advance.
This is how I would have written it as it's quite a bit cleaner. A few things I noticed that you may want to take note of:
It's good practice to initiate variables when you declare them.
Read up about continue and break in loops as well as when to use a do-while or a while loop.
Happy coding!
const int SENTINEL = -1;
int main() {
int payroll_sum = 0;
int payroll = 0;
int counter = 0;
while (payroll != SENTINEL) {
cout << "Enter a payroll amount (-1 to end): ";
cin >> payroll;
if(payroll == SENTINEL) break;
if((payroll < SENTINEL)){
cout << "\nError!\nPlease enter a correct value.\n" << endl;
continue;
}
else {
payroll_sum += payroll;
counter++;
}
}
cout << "\n\nTotal payroll amount is: " << payroll_sum;
cout << "\nTotal number of entries is: " << counter;
return 0;
}
Use
continue;
Instead of
int main(payroll);
And also, initialize payroll_sum by using
payroll_sum=0
Before the loop. Also, remove
if(payroll == SENTINEL){
payroll_sum += 1;
counter -= 1;
}
And change the last two couts to
cout << "\n\nTotal payroll amount is: " << payroll_sum+1;
cout << "\nTotal number of entries is: " << counter-1;
Seems like a simple question about condition logic. There are plenty of different ways to structure your if conditions but one way that would be more efficient than your current code could be:
while(true)
{
cout << "Enter a payroll amount (-1 to end): ";
cin >> payroll;
if(payroll == SENTINEL)
break;
if((payroll < SENTINEL))
{
cout << "\nError!\nPlease enter a correct value.\n" << endl;
int main(payroll);
}
else
{
payroll_sum += payroll;
counter += 1;
cout << "\n";
}
}
If you don't like using while(true) I can provide another example. Cheers
I have to make my homework. It is console application which uses an array of structs that keep information about a computer(brand, year of manufactoring, weight and inventory number). So I wrote a completely working program, but I want to use a dynamic array, because I dont know how many records the user will input.
Is there way to do this. To add new records in array until the user say n/N? Any suggestions?
This is my version of program:
#include "stdafx.h"
#include <iostream>
using namespace std;
struct ComputerInfo
{
char computerMark[20], invertarNumber[6];
unsigned int year;
float weight;
};
ComputerInfo computerArray[300];
ComputerInfo AddComputers(ComputerInfo compterArray[], int counter)
{
cout << "Enter mark of the computer: ";
cin >> computerArray[counter].computerMark;
cout << "Enter year of establish: ";
cin>> computerArray[counter].year;
while ((computerArray[counter].year < 1973)
|| (computerArray[counter].year > 2013))
{
cout << "INVALID YEAR!!!" << endl;
cout << "Enter year of establish: ";
cin>> computerArray[counter].year;
}
cout << "Enter computer weidth: ";
cin >> computerArray[counter].weight;
cout << "Enter computer invertar number(up to six digits): ";
cin >> computerArray[counter].invertarNumber;
return computerArray[counter];
}
void ShowRecords()
{
int counter = 0;
while (computerArray[counter].year != 0)
{
cout << "Mark: " << computerArray[counter].computerMark << endl;
cout << "Year: " << computerArray[counter].year << endl;
cout << "Weidth: " << computerArray[counter].weight << endl;
cout << "Inv. number: " << computerArray[counter].invertarNumber << endl << endl;
counter++;
}
}
void MoreThanTenYearsOld(ComputerInfo computerArray[])
{
int counter = 0;
float counterOldComputers = 0;
float computerPer = 0;
while (computerArray[counter].year == 0)
{
if (computerArray[counter].year <= 2003)
{
counterOldComputers++;
}
counter++;
}
computerPer = counterOldComputers / 3;
cout << endl;
cout << "Percantage of old computers is: " << computerPer << endl;
}
int main()
{
int counter = 0;
float computerPer = 0;
char answer = 'y';
for (int i = 0; i <= 299; i++)
{
strcpy(computerArray[i].computerMark,"");
}
while((answer == 'Y') || (answer == 'y'))
{
computerArray[counter] = AddComputers(computerArray, counter);
cout << endl;
cout << "Do you want to enter more records (Y/N): ";
cin >> answer;
cout << endl;
counter++;
}
MoreThanTenYearsOld(computerArray);
return 0;
}
Yes. Instead of your array, use
std::vector<ComputerInfo> computerArray;
and you can add as many objects as you want:
ComputerInfo c;
// read the data
computerArray.push_back(c);
now, computerArray[0] will have the info in c.
You'll need to #include <vector>.
Also, instead of char computerMark[20] you can use a std::string.
You have two options:
1) Use std::vector instead of an array. This is a very powerful tool and certainly worth learning how to use.
2) Dynamically allocate the array and resize it as you add more items. Basically this means writing your own version of std::vector. This is a good way to strengthen your programming skills. You will learn what goes into writing standard classes and functions. However, I advise using std::vector in more serious programming because it has already been thoroughly tested and debugged.