c - C 中的 GMP 库 - 如何使添加更精确?

标签 c calculator precision addition gmp

试图在 C 上使用 GMP 库创建一个简单的精确计算器,我在测试我的程序时遇到了一个相当意外的错误;
2 + 2.22222 = 4.22221999999999999999。

这是我在 GMP 中使用的功能;

mpf_add(res, f1, f2); //with res as result already initilized, f1 and f2 as the values

至于打印功能;
gmp_printf("%.Ff\n", getExprValue()) //with getExprValue the calculating function that has the line above.

编辑 :

这是完整的代码;
    int isValidExpression(const char *str) // to check the input
{
    int res;
    char validOps[6] = {'+', '-', '*', '/', '^', '\0' };

    mpf_init(f1);
    mpf_init(f2);

    // RES = 3 WHEN SYNTAX OK
    res = gmp_sscanf(str, "%Ff %c %Ff", f1, &op, f2);

    // RES = 4 WHEN OPERAND OK
    if(strchr(validOps, op)) res++;

    int exprCounter = 0;
    char* token = strtok(str, " +-*/^");
    while(token != NULL)
    {
        // TOO MANY WORDS IN THE EXPRESSION
        ++exprCounter;
        if(exprCounter > 2) res = 0;

        // TAKE THE NEXT WORD
        token = strtok(NULL, " +-*/^");
    }
    return (res==4);
}
mpf_t* getExprValue() //Working on the operand
{
    static mpf_t res;
    mpf_init(res);


    switch(op)
    {
    case '+':
        mpf_add(res, f1, f2);
        break;

    case '-':
        mpf_sub(res, f1, f2);
        break;

    case '*':
        mpf_mul(res, f1, f2);
        break;

    case '/':
        mpf_sgn(f2) != 0 ? mpf_div(res, f1, f2) : printf("Division by ");
        break;

    case '^':
        mpf_pow_ui(res, f1, mpf_get_si(f2));
        break;
    }
    return res;
}

至于主要;
char input[MAX_INPUT];
while(gets(input))
{
    if(strcmp(input, "exit") != 0)
    {
        isValidExpression(input) ? gmp_printf("%.Ff\n", getExprValue()) : puts("Expression error");

    }
    else
    {
        puts("Exiting...");
        break;
    }
}

最佳答案

问题是您正在尝试十进制算术并使用浮点数。您需要使用十进制算术库对十进制数进行精确计算。

关于c - C 中的 GMP 库 - 如何使添加更精确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41881401/

相关文章:

在 Solaris 中编码 pmap

android - 如何从应用程序调用 Android 计算器

java - 在 Java 和 C++ 中增加计数器的最佳方法?

javascript - 添加 sum 并将其替换为 3 个选择

PHP高精数学-性能

c - 如何将 double 转换为 unsigned 货币?

math - float 学有问题吗?

c - 当参数之一是函数调用时,printf 如何在 c 中工作

c - 未知数量的用户输入整数

c - 我有一个节点哈希表。如何打印哈希表中每个节点的每个单独值?