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
将数字乘以合适的比例因子,将所有有效数字移动到小数点的左侧.然后围绕并最终反转操作:
#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)
但正如@PascalCuoq指出的那样:舍入值可能无法准确表示为浮点值.
#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
如果要将浮点数打印为字符串,请使用 simple sprintf()。为了将其输出到控制台,您可以使用printf():
printf("My float is %.6f", myfloat);
Run Code Online (Sandbox Code Playgroud)
这将输出 6 位小数的浮点数。
| 归档时间: |
|
| 查看次数: |
13016 次 |
| 最近记录: |