AC程序将浮点数舍入到n位有效数字?

ste*_*km3 8 c c++ floating-point

假设我有一个float.我想将它四舍五入到一定数量的有效数字.

就我而言n=6.

所以说漂浮是 f=1.23456999;

round(f,6) 会给 1.23457

f=123456.0001 会给 123456

谁知道这样的例行公事?

它可以在网站上找到:http://ostermiller.org/calc/significant_figures.html

Dan*_*ger 7

将数字乘以合适的比例因子,将所有有效数字移动到小数点的左侧.然后围绕并最终反转操作:

#include <math.h>

double round_to_digits(double value, int digits)
{
    if (value == 0.0) // otherwise it will return 'nan' due to the log10() of zero
        return 0.0;

    double factor = pow(10.0, digits - ceil(log10(fabs(value))));
    return round(value * factor) / factor;   
}
Run Code Online (Sandbox Code Playgroud)

测试:http://ideone.com/fH5ebt

但正如@PascalCuoq指出的那样:舍入值可能无法准确表示为浮点值.


Dav*_*rtz 5

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

char *Round(float f, int d)
{
    char buf[16];
    sprintf(buf, "%.*g", d, f);
    return strdup(buf);
}

int main(void)
{
    char *r = Round(1.23456999, 6);
    printf("%s\n", r);
    free(r);
}
Run Code Online (Sandbox Code Playgroud)

输出是:

1.23457


rek*_*ire 1

如果要将浮点数打印为字符串,请使用 simple sprintf()。为了将其输出到控制台,您可以使用printf()

printf("My float is %.6f", myfloat);
Run Code Online (Sandbox Code Playgroud)

这将输出 6 位小数的浮点数。

  • 这将为您提供 6 位小数,而不是 6 位有效数字。 (3认同)