我正在尝试将MPFR编号转换为字符串然后再返回。我正在使用的代码是:
int base = 10;
int input = 25;
mpfr_t number;
mpfr_inits2(53, number, (mpfr_ptr) 0);
mpfr_set_d(number, input, MPFR_RNDD);
mpfr_printf ("mpfr = %.17Rg\n", number);
char* str = NULL;
mpfr_exp_t e;
str = mpfr_get_str (NULL, &e, base, 0, number, MPFR_RNDN);
cout << "str: " << str << endl;
cout << "e: " << e << endl;
mpfr_t back;
mpfr_inits2(53, back, (mpfr_ptr) 0);
mpfr_set_str(back, str, base, MPFR_RNDD);
mpfr_set_exp(back, e);
mpfr_printf ("back = %.17Rg\n", back);
mpfr_free_str (str);
这给了我输出:
mpfr = 25
str: 25000000000000000
e: 2
back = 2.7755575615628914
如果我将基数更改为2,那么我得到正确的输出
mpfr = 25
str: 11001000000000000000000000000000000000000000000000000
e: 5
back = 25
但如果我将输入更改为0,我会再次收到错误的mpfr编号:
mpfr = 0
str: 00000000000000000000000000000000000000000000000000000
e: 0
back = 0.8125
我究竟做错了什么?
答案 0 :(得分:1)
代码中的错误是base
是基础char buffer[64];
sprintf (buffer, ".%s@%ld", str, (long) e);
mpfr_set_str (back, buffer, base, MPFR_RNDD);
mpfr_printf ("back = %.17Rg\n", back);
中的指数,而不是基数2中的指数。您需要类似的东西(对于此特定情况非常简单,仅对于正数) :
@
(e
代替通常的mpfr_set_exp
,允许代码支持大于10的基数。)
另请注意,在第三次测试中,如果输入0,则在值0上调用mpfr_set_exp
,这会产生无效的MPFR编号。在MPFR 4中,.data([data])
对0没有影响,这更清晰。