使用gmp库和有理数(mpq_t
),我试图以小数分数打印出合理的小数,小数分隔符后的数字。
我目前的做法是写入char
缓冲区,对缓冲区中的数字进行舍入,然后将其打印出来。它有效,但我觉得我是太过于复杂,即:
char
缓冲区1
,例如)问题:
有没有办法做得更好?更简单?我完全错过的东西?
请注意,理性的分子和分母可以“任意”大。
以下是相关代码,mpz1
,mpz2
属于mpz_t
类型且已初始化,我正在转换的理性位于mpq1
:
编辑:此代码中某处至少有一个错误,但我不想找到它,因为无论如何我都重写了它。
/* We might need to insert a digit between the sign
* and the rest of the number:
* deal with the sign explicitly
*/
int negative = 0;
if (mpz_sgn(mpq_numref(mpq1)) == -1) /* negative number */
negative = 1;
/* Calculate the integer part and the remainder */
mpz_tdiv_qr(mpz1, mpz2, mpq_numref(mpq1), mpq_denref(mpq1));
if (mpz_cmp_ui(mpz2, 0) == 0) { /* remainder is 0 */
gmp_printf("%Zd", mpz1);
return;
}
/* What is the maximum possible length of the decimal fraction? */
size_t max_len =
mpz_sizeinbase(mpz1, 10) /* length of the string in digits */
+ 1 /* '\0' terminator */
/* + 1 possible minus sign: dealing with it explicitly */
/* + 1 decimal point: dealing with it explicitly */
+ real_precision + 1; /* precision and the extra digit */
/* Prepare the buffer for the string */
/* ... */
/* block of sufficient size at char *str */
char *end = str;
end += gmp_sprintf(end, "%Zd", mpz1);
char *dec_point = end;
/* Calculate the fractional part and write it to the buffer:
* to round correctly, we need to know one more digit than
* the precision we are aiming at
*/
mpz_abs(mpz2, mpz2);
mpz_ui_pow_ui(mpz1, 10, real_precision + 1);
mpz_mul(mpz2, mpz2, mpz1);
mpz_tdiv_q(mpz2, mpz2, mpq_denref(mpq1));
end += gmp_sprintf(end, "%Zd", mpz2);
size_t extra_zeros = real_precision + 1 - (end - dec_point);
char *p = end - 1; /* position of the extra digit */
/* Do we need to round up or not? */
int roundup = 0;
if (*p > '4')
roundup = 1;
/* Propagate the round up back the string of digits */
while (roundup && p != str) {
--p;
++*p;
if (*p > '9')
*p = '0';
else
roundup = 0;
}
/* Move end back to the first non-zero of the fractional part */
p = end - 2; /* position of the last significant digit */
while (*p == '0' && p != dec_point - 1)
--p;
end = p + 1; /* the new end */
/* Output the number */
if (negative) /* minus sign */
putc('-', stdout);
if (roundup) /* overflow */
putc('1', stdout);
/* Integer part */
p = str;
while (p != dec_point) {
putc(*p, stdout);
++p;
}
if (p == end) /* There is no fractional part after rounding */
return;
/* Fractional part */
putc('.', stdout);
while (extra_zeros-- != 0)
putc('0', stdout);
while (p != end) {
putc(*p, stdout);
++p;
}
答案 0 :(得分:1)
如果你想将无符号有理数值舍入到最接近的整数,你需要加0.5,然后只显示整数部分。
对于小数点后的1位数,您需要添加0.05。
对于小数点后的2位数,您需要添加0.005。
对于小数点后的n
位,您需要添加5 / ( 10**(n+1) )
。
答案 1 :(得分:0)
仅仅为了子孙后代,我最终做的事情确实与布兰登的答案相符。由于我已经签署了理由,我会做以下事情(不详细说明):
1/(2*10^precision)
添加到正数,或-1/(2*10^precision)
添加到否定理性