开发者

Creating a calculator in C

How can I create a calculator in C without using if else and switch case ?

Here is the code so far :

void main()

{

    int a,b,sum,sub,pro,divide; /** sum is for addition,,sub is for subtraction,,pro is for product,,divide is for division**/
    char operator;
    clrscr();      
    printf("enter a value:");
    scanf("%d",&a);      
    printf("enter another value:");
    scanf("%d",&b);
    printf("enter a operator:");
    scanf("%c",&operator);

    operator=='+';
    sum=a+b;
    printf("\nAnswer=%d",sum);
    operator=='-'
   sub=a-b;开发者_运维百科
    printf("\nAnswer=%d",sub);
    operator=='*';
    pro=a*b;
    prinf("\nAnswer=%d",pro);
    operator=='/';
    printf("\nAnswer=%d",divide);
    getch();  

}


The following should do the trick. It avoids using if else and switch by taking advantage of the fact that comparing the operator to either of +, -, * or / will return 1 for only one of the comparisons and 0 for the rest. Therefore the result is the sum of these comparisons, multiplied by the mathematic expression that corresponds to each operator:

#include<stdio.h>

main(){
    float a,b,result;
    char oper [2];
    printf("enter a value:");
    scanf("%f",&a);
    printf("enter another value:");
    scanf("%f",&b);
    printf("enter an operator:");
    scanf("%1s", oper);
    result = (oper[0] == '+') * (a + b) +
             (oper[0] == '-') * (a - b) +
             (oper[0] == '*') * (a * b) +
             (oper[0] == '/') * (a / b);
    printf("%4.2f %s %4.2f = %4.2f\n", a, oper, b, result);
}

When saved to a file called calculator.c the following command will compile it:

gcc calculator.c

The output will be called a.out and it can be run like this:

./a.out
enter a value:24
enter another value:4
enter an operator:/
24.00 / 4.00 = 6.00

I've been using gcc (GCC) 4.4.1 20090725 (Red Hat 4.4.1-2) but I'm sure other versions will work just as well.

Let me know if I pass your assignment ;-)


Actually, I've thought of a solution that satisfies the condition of the assignment and isn't totally retarded.

You can create a function for each operation; it takes the two inputs as arguments and returns the result. You can then create a table of pointers to those functions, indexed by the operator character.

Then you can execute the function through the pointer.

int multiply(int a, int b)
{
  return a * b;
}

/**
 * do the same for add, subtract, and divide
 */

int main(void)
{
  int a, b;
  char op;
  /** 
   * create an array of pointers to functions indexed by 
   * character values; we will only be using four of these entries,
   * but this allows us to index the array using the operator
   * character directly instead of having to do any mapping.
   * We're trading some unused space for simplicity.
   */
  int (*func_table[128])(int, int);

  /**
   * Set the table entries for each operator.
   */
  func_table['*'] = multiply;
  /**
   * Do the same for each of '-', '+', '/'
   */
  ... 

  /**
   * After reading in a, b, and the operator, execute
   * the function through the lookup table
   */
  result = (*func_table[op])(a, b);

Presto; no control structures.

I was reluctant to post this for a couple of reasons. First, it basically gives away the store. Second, I doubt you've discussed function pointers in class yet. I have no idea what your instructor expects; I doubt it's this.


You should be able to solve it by pushing the operator and values onto a stack, and then just "execute" the stack.

Since this probably is a homework, I leave you with the task to implement the it :)


As is remarked in the comments, the code is ridden with problems. Try this simple switch-case statement:

switch(op) {
    case '*': printf("%d",a*b); break;
    case '/': printf("%d",a/b); break;
    case '+': printf("%d",a+b); break;
    case '-': printf("%d",a-b); break;
    default: printf("Unknown operator."); break;
}

You'll handle the rest, right?

[EDIT]

OK, I thought it was SUPPOSED to use a switch-case.

How about this:

int result = 0;
result = (op == '*') ? a * b : result;
result = (op == '/') ? a / b : result;
result = (op == '+') ? a + b : result;
result = (op == '-') ? a - b : result;
printf("%d",result);

There's no if-else or switch-case :) You can also nest the statements if you wish (but that's unreadable).


In C comparisons have a value. 1 if true, 0 if false. Maybe you can use that instead of the forbidden if

(operator == '+') /* this is either 0 or 1 */
(operator == '-') /* this is either 0 or 1 */
(operator == '*') /* this is either 0 or 1 */
(operator == '/') /* this is either 0 or 1 */


void main()

{

    int a,b,sum,sub,pro,divide; /** sum is for addition,,sub is for subtraction,,pro is for product,,divide is for division**/
    char operator;
    clrscr();      
    printf("enter a value:");
    scanf("%d",&a);      
    printf("enter another value:");
    scanf("%d",&b);
    printf("enter a operator:");
    scanf("%c",&operator);

    operator=='+'? printf("%d,a+b"): ;
    //same goes for all the other operators

    getch();  

}


i think it gonna be work like this too

# include "stdio.h"
# include "conio.h"
 void main()
    {
float a , b;
char c;

printf("Value 1:");
scanf("%f",&a);
printf("value 2:");
scanf("%f",&b);
printf("Enter a operator[ + - * /]\n");
c=getche();

(c=='+')&&(printf("\nAnswer is:%3.2f",a+b));
(c=='-')&&(printf("\nAnswer is:%3.2f",a-b));
(c=='*')&&(printf("\nAnswer is:%3.2f",a*b));
(c=='/')&&(printf("\nAnswer is:%3.2f",a/b));
getch();
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜