本文介绍了四舍五入有效数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个值为0.00004876544的浮点数。

例如,0.00004876544会读取0.000049。

如何获得显示在第一个重要数字后的小数点后两位?解决方案我没有通过编译器来检查它,但是这里是算法的基本问题(从答案转换到):



<$($)
$ b <$ (float)round:(float)num toSignificantFigures:(int)n {
if(num == 0){
return 0;
}

double d = ceil(log10(num int power = n - (int)d;

double magnitude = pow(10,power);
长移=圆(数量级);
返回移动/幅度;



$ b $ p
$ b

重要的是要记住Objective-C是C的一个超集,所以在C中有效的任何东西在Objective-C中也是有效的。此方法使用 math.h 中定义的C函数。


In Xcode /Objective-C for the iPhone.

I have a float with the value 0.00004876544. How would I get it to display to two decimal places after the first significant number?

For example, 0.00004876544 would read 0.000049.

解决方案

I didn't run this through a compiler to double-check it, but here's the basic jist of the algorithm (converted from the answer to this question):

-(float) round:(float)num toSignificantFigures:(int)n {
    if(num == 0) {
        return 0;
    }

    double d = ceil(log10(num < 0 ? -num: num));
    int power = n - (int) d;

    double magnitude = pow(10, power);
    long shifted = round(num*magnitude);
    return shifted/magnitude;
}

The important thing to remember is that Objective-C is a superset of C, so anything that is valid in C is also valid in Objective-C. This method uses C functions defined in math.h.

这篇关于四舍五入有效数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:50