c - GMP 计算器卡在幂数上

标签 c calculator gmp

我刚刚为 gmp 计算器编写了代码。加法和乘法工作无可挑剔,但就求幂而言,它要么停止要么打印无限数量的零。

如何使用gmp power函数使其工作?

gmptest.c

#include <stdio.h>          
#include <gmp.h>

int main(int argc, char *argv[])
{
    mpf_t x1;
    mpf_t x2;
    mpf_t result;
    char operation;
    char x_1[20];
    char x_2[20];
    printf("Choose between *,+ and ^\n");
    scanf("%c\n", &operation);

    fgets(x_1, sizeof(x_1), stdin);
    fgets(x_2, sizeof(x_2), stdin);

    mpf_init(x1);
    mpf_init(x2);
    mpf_init(result);
    mpf_set_str(x1, x_1, 10);
    mpf_set_str(x2, x_2, 10);

    switch(operation) {
    case '+':
        mpf_add(result, x1, x2);
        break;
    case '^':
        mpf_pow_ui(result, x1, x2);
        break;
    case '*':
        mpf_mul(result, x1, x2);
        break;
    default:
        printf("Error! operator is not correct");
        break;
    }

    gmp_printf("%0.20Ff", x1);
    printf(" %c ", operation);
    gmp_printf("%0.20Ff", x2);
    gmp_printf(" = %0.20Ff\n\n", result);

    return 0;
}

最佳答案

mpf_pow_ui() 的签名是

void mpf_pow_ui (mpf_t rop, const mpf_t op1, unsigned long int op2)

如果你想要一个浮点指数,使用 MPFR图书馆,它在 GMP 之上工作。

关于c - GMP 计算器卡在幂数上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34331156/

相关文章:

floating-point - 58.85显示为58.84999999999

iphone - 如何在 Objective-C 中进行十进制格式化?

android - 简单的安卓计算器

c - 使用 GMP 库执行文件时出错

c - 如何用字符串中的 1024 位数字初始化 gmp 中的 mpz_t?

c - dup 系统调用的奇怪行为

没有 libiconv 的 C 字符串编码 UTF8

ios - 为 ios 7 armv7s 编译 GMP

c - 将值填充到一维数组中

c++ - 将二维字符串数组传递给 C++ 中的函数