Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Math operation with char instead of + – * /

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading