Home > Software engineering >  Recall the char function
Recall the char function

Time:05-23

I'm very new to programming, and I'm doing a simple bot in C, that has a calculator function. I'm having some trouble in this piece of code:

char operation = get_char("Insert the mathematical operation: ");
float x = get_float("X: ");
float y = get_float("Y: ");
if (operation == 43)
{
    float result = (x   y);
    int rresult = round(result);
    printf("X   Y = %i\n", rresult);
    string confirmation = get_string("Need to do something more? ");
    if (strcmp(confirmation, "Y") == 0)
    {
        return operation;
    } 

As you can see, this calculator ask the user for a char (*, /, or - [its everything defined in the other parts of the code, I will not post it here just to be brief] that defines the math operation and then, after doing the calculation and printing the result, asks the user if he wants to do more calculations. If the answer is "Y" (yes), I want to restart this piece of code, asking for the char and the floats, and doing everything. I want to know the simplest way to do this, without making the code looks bad designed. Also, I'm using CS50 IDE.

CodePudding user response:

I don't have CS50, therefore, plain C. The construct you might want to use is a do-while loop.

#include <stdio.h>
#include <math.h>

char get_char(char * msg) {static char c; printf("%s", msg); scanf(" %c", &c); return c;}
float get_float(char * msg) {static float f; printf("%s", msg); scanf(" %f", &f); return f;}

int main() {
    char confirmation = 'n';
    do {
        char operation = get_char("Insert the mathematical operation: ");
        float x = get_float("X: ");
        float y = get_float("Y: ");
        if (operation == ' ') {
            float result = (x   y);
            printf("Result in float: %f\n", result);
            int rresult = round(result);
            printf("X   Y = %i\n", rresult);
        }
        confirmation = get_char("Need to do something more [y/n]? ");
    } while (confirmation == 'y');
    return 0;
}
$ gcc -Wall dowhile.c
$ ./a.out            
Insert the mathematical operation:  
X: 0.11
Y: 0.88
Result in float: 0.990000
X   Y = 1
Need to do something more [y/n]? y
Insert the mathematical operation:  
X: 0.1
Y: 0.1
Result in float: 0.200000
X   Y = 0
Need to do something more [y/n]? n
$ 
  • Related