'i write a code for calculator in langage c ,in i write 1+1+1+1 in float i return not result but for 1+1=2 i find result i want to fix

i write a code for calculator in langage c ,in i write 1+1+1+1 in float i return not result but for 1+1=2 i find result i want to fix.

i use calculate function for a som ,and parsemath for result

the code of application :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

float calculate(float x, float y, char op)
{
    if (op == '+')
    {
        return x + y;
    }
    return -1;
}

char *parseMath(const char *s, char *result)
{
    float x;
    float y;
    char op;
    sscanf(s, "%f%c%f", &x, &op, &y);
    int offset = snprintf(NULL, 0, "%f%c%f", x, op, y);
    const char *rest = s + offset;
    float temp = calculate(x, y, op);
    printf("%zu\n", strlen(result));
    float done = rest[0] == '\0';
    sprintf(result, "%f%s", temp, rest); //%.2f
    if (done)
    {
        return result;
    }
    else
    {
        return parseMath(result, result);
    }
}

int main(void)
{
    const char *exp = "1+1+1+1";
    char *result = malloc(strlen(exp) + 1);
    *result = 0;

    char *output = parseMath(exp, result);
    printf("output: %s\n", output);
}


Solution 1:[1]

The strtof function returns the position after parsing a float.

float x = 0, y;
char *next = s;
while(*s) {
    y = strtof(next, &s);
    if (s == next) break;
    op = *s++;
    if (op == 0) break;
    x = calculate(x, y, op);
    next = s;
}

Note that this gets more complicated if you want to add precedence.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 stark