回忆一下 char 函数

Recall the char function

我是编程新手,我正在用 C 编写一个简单的机器人,它具有计算器功能。我在这段代码中遇到了一些问题:

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;
    } 

如您所见,此计算器要求用户输入一个字符 (*、/、+ 或 - [它在代码的其他部分中定义的所有内容,我不会 post 这里只是为了be brief] 定义数学运算,然后在计算并打印结果后,询问用户是否要进行更多计算。如果答案是“Y”(是),我想重新启动这段代码, 询问 char 和浮点数, 并做所有事情。我想知道最简单的方法来做到这一点, 而不会使代码看起来设计糟糕。 另外,我正在使用 CS50 IDE.

我没有 CS50,因此,纯 C。您可能想要使用的构造是 do-while 循环。

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

char get_char(char * msg) {char c; printf("%s", msg); scanf(" %c", &c); return c;}
float get_float(char * msg) {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
$