ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Hi there,
I am looking for any code people are happy to supply in helping me to create a Calculator in C language.
There are a lot of Calculators written in C++, however I was wondering if anyone has any knowledge of a C Calc.
The calculator needs to not accept any other entry that that of integers only, therefor if 2b + 2b were entred an error would occur. Yet if 2 + 2 were entered, the obvious answer would be displayed. The calculator also needs to accept *, - , / as well.
I remember this was an assignment problem in my first year. I did it in pascal using recursion with great difficulty. But later I came to know that this a standard problem and can be easily solved using a stack. The Idea is to convert the normal expression to postfix expr and evaluate it using a stack. Search google for more info. If you just want 2 variables to be handled at a time you can just use a switch statement to solve it.
--Sarin
I didn't know that (postfix, stack ...)
Is it possible to handle precedences (i.e. do '*' and '/' before '+' and '-') as well with a stack? In other words, can it handle correctly somthing like this:
if you just read a line, it's quite easy (recursion may be needed to calculate expressions in () ). A calculator is a popular projects for students during programming courses, so you should be able to find examples (also ideas from C++ code).
Here below is what I have found and worked with up to this point.
What I need to achieve with the program is error checking and reporting on the numbers, ie if 2b + 2 were entered, then an error would follow, in the case of this code the error is displayed only if the error is occuring with the use of the +, -, * & / key.
Any further thoughts on this exercise?
Feel free to include within the code below whatever you feel may work, and post back if you prefer.
/*Print out some information about the program*/
printf("\nThis program is a simple calculator.\n");
printf("It is able to do the four standard opeartions.\n");
printf("Enter the equation in the following fomrat:\n");
printf("\t[first value][operand][second value]\n");
printf("type '0q0' to quit\n\n");
/*This loop keeps the user in the program untill he wants to
*quit which is accomplies by typing 0q0
*/
while(!(operand == 'q' || operand == 'Q')) {
/*print the prompt and wait for the user to enter an equation*/
printf(": ");
scanf("%lf%c%lf%c", &value1, &operand, &value2, &junk);
/*look for the operand entered and perform the operation asked
*for by the user. If operand is not +, - ,*, or / then
*print out an error
*/
switch(operand) {
case '+': {
printf("\t%lf\n", value1 + value2);
break;
}
case '-': {
printf("\t%lf\n", value1 - value2);
break;
}
case '/': {
printf("\t%lf\n", value1/value2);
break;
}
case '*': {
printf("\t%lf\n", value1 * value2);
break;
}
case 'q':
case 'Q': {
break;
}
default: {
printf("**error: operand %c not known**\n", operand);
}
}/*end switch*/
Just looking at the program again myself, appreciate thoughts if possible. Is it possible to have some kind of "If" statement within the code along the idea of this kind of pseudocode:
Set value1 & value2 to Double
IF value1, value2 character Then
Print: Error "You must only have numbers for calculations, please try again."
Else
Continue Program
If that work, where and how would I put it?
Once again please feel free to insert it into the code, for trial.
Many thanks.
Hmm, you need to read them as strings. It's a better idea.
Or maybe just one string (before switch), then searching for errors and switch at the end.
Something like that (line is char[512]):
Code:
int i=0;
while((line[i]>='0') && (line[i]<='9')) i++;
if((line[i]=='+')||(line[i]=='-')||(line[i]=='*')||(line[i]=='/')) i++;
else {
printf("You must only have numbers for calculations, please try again.");
return;
}
while((line[i]>='0') && (line[i]<='9')&&(line[i]!='\0') i++;
Of course, it's not perfect. It won't handle spaces before a number and +-*/ and it won't handle brackets. But I suppose it's now easier.
Oh, and you need to add a function to change the numbers (in strings) into integers or floats.
If you want to avoid spaces, you can do so in the begining.
( I haven't seen your code fully. So consider this as the code only to remove white spaces. )
i=0;
j=0;
while ( line[i] != '\0' )
{
if ( !isspace(line[i]) )
{
line2[j]=line[i];
j++;
}
i++;
}
line2[j]='\0';
And then make use of line2 in place of line.
--Sarin
So by white space am I to take it you mean a (-> <-) space as indicated between the arrows above. The code you have given me will diregard the code and allow the calculator to function with out error on a space between integer and operand?
Well thankyou and I'll see where I can include it best for operating the program.
i have finished the computations for simple numbers and numbers with functions... now my problem is how do i make the program compute first for the multiplication(*) division(/) before addition(+) subtraction(-)? Please.. i need an idea.. thanx advance ^^
***Another thread back from the dead***
The solution will depend upon what is expected of you.
If prefix notation has been discussed then use that along with a stack.
If none of that has been discussed then you are probably expected to use a cunning combination of if statements and function calls.
i have finished the computations for simple numbers and numbers with functions... now my problem is how do i make the program compute first for the multiplication(*) division(/) before addition(+) subtraction(-)? Please.. i need an idea.. thanx advance ^^
I think that starting your own thread might help. You might also consider how you picture the operator precedence working - maybe a few test cases. Also, multiple passes and/or parenthesis may be useful mechanisms.
Edit: I guess I took a while to page through the old thread and post my reply. The post by [graemef] should point you in the right direction.
Last edited by nmh+linuxquestions.o; 03-27-2007 at 02:45 AM.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.