Home > Blockchain >  Math operation with char instead of - * /
Math operation with char instead of - * /

Time:09-15

So my code will ask the user for a input of what operation he wants to perform ( - * /) and then two numbers.

Based on that, a bunch of if statements will figure out what type of operation the user wants and them calculate the result.

I'm trying to reduce all of that to a single function, how can I make that?

This is what I've tried but it did not work:R is the result, N1 and N2 are the numbers, and the char OP is the user input on what type of math operation he wants.

This is my old code: I want to reduce all of those if functions to something like the image, a single line that could do all of them.

float N1, N2, R;
char OP;

printf("Type the type of operation you want(  - * /):");
scanf("%c",&OP);
fflush(stdin);

printf("Type your first number:");
scanf("%f",&N1);
fflush(stdin);

printf("Type your second number:");
scanf("%f",&N2);
fflush(stdin);

if (OP==' ') //ADDITION
{
    R=N1 N2;
    
    if (R==(int)R)
    {
      printf("Your result is: %i \n" ,(int)R);  
    }
    else
    {
        printf("Your result is: %.2f \n",R); 
    }
}

else if (OP=='-') //SUBTRACTION
{
    R=N1-N2;
    
    if (R==(int)R)
    {
      printf("Your result is: %i \n",(int)R);  
    }
    else
    {
        printf("Your result is: %.2f \n",R); 
    }
}

else if (OP=='*') //MULTIPLICATION
{
    R=N1*N2;

    if (R==(int)R)
    {
      printf("Your result is: %i \n",(int)R);  
    }
    else
    {
        printf("Your result is: %.2f \n",R); 
    }
}

else if (OP=='/') //DIVISION
{
    R=N1/N2;

    if (R==(int)R)
    {
      printf("Your result is: %i \n",(int)R);  
    }
    else
    {
        printf("Your result is: %.2f \n",R); 
    }
}

else
{
    printf("Error. Please try again.");
}

system("pause");
return 0;

CodePudding user response:

You can’t. There needs to be a branching structure somewhere.

A common (and good) way to do it is to build a lookup table for operatorfunction.

For really fast stuff ( O(1) ), you can build yourself a perfect hash map.

For a homework over four operators, just use an O(n) lookup.

  • Related