Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何四舍五入到最接近的10次方?_C++_Objective C_C_Rounding_Floor - Fatal编程技术网

C++ 如何四舍五入到最接近的10次方?

C++ 如何四舍五入到最接近的10次方?,c++,objective-c,c,rounding,floor,C++,Objective C,C,Rounding,Floor,我甚至找不到这个的搜索关键字。 请考虑此代码: float inputValue = getInputValue(); float resultValue; if (inputValue < 0.1f) { resultValue = 0.01f; } else if (inputValue < 1.0f) { resultValue = 0.1f; } else if (inputValue < 10.0f) { resultValue = 1.0f

我甚至找不到这个的搜索关键字。 请考虑此代码:

float inputValue = getInputValue();
float resultValue;

if (inputValue < 0.1f) {
    resultValue = 0.01f;
}
else if (inputValue < 1.0f) {
    resultValue = 0.1f;
}
else if (inputValue < 10.0f) {
    resultValue = 1.0f;
}
else {
    resultValue = 10.0f;
}
float inputValue=getInputValue();
浮动结果值;
if(输入值<0.1f){
结果值=0.01f;
}
否则如果(输入值<1.0f){
结果值=0.1f;
}
否则如果(输入值<10.0f){
结果值=1.0f;
}
否则{
结果值=10.0f;
}
等等。必须有一个更优雅的方法来做到这一点。 我想解决办法很简单,但我现在试着找一个方法,花了2个小时读了关于圆形、天花板、地板……找不到


有人有什么想法吗?

我相信有一种更简单的方法,它不试图从第一原则出发,而是:

float inputValue = getInputValue();

float log10 = floorf(log10f(inputValue));
float modulo = powf(10.0f, log10);
inputValue -= fmodf(inputValue, modulo);

编辑:事实上,我想我假设你想要230到200,0.73到0.7,等等,所以这可能不是答案。我把它放在一边,因为不管怎样,它可能会有所帮助。

您的代码没有做您认为它做的事情。对于任何小于100(包括0.001)的值,resultValue将设置为10。你需要按相反的顺序检查

powf(10.0f, floorf(log10f(value)))

首先,我要写下这个函数的规范:对于什么输入值,您希望得到什么输出值?1.01e17的输入是否需要1.0e17?如果输入为0或-1怎么办

这是一个BigInteger版本。 我需要下一个(而不是最近的)10次方,但你可以看到这个想法:

import java.math.BigInteger;

class A {
    public static void main(String[]args) {
        System.out.println("hi");
    for (long v : new long[] {0,1,2,9,10,11,99,100,101,12345678,123456789012345678L,1234567890123456789L}) {
            System.out.println(""+v+" ==> "+nextPowerOf10(v));
        }
    }
    static long nextPowerOf10(long v) {
        return BigInteger.TEN.pow((int)Math.max(0,1+Math.floor(Math.log10(v)))).longValue();
    }
}
如果你想让它在10的幂上表现不同,可以使用上面的
1+Math.floor
(0/1,floor/ceil/round)。顺便问一下,OP在“最近的”下是什么意思?在线性或对数尺度上是最近的?最近的大还是最近的小

>java A
hi
0 ==> 1
1 ==> 10
2 ==> 10
9 ==> 10
10 ==> 100
11 ==> 100
99 ==> 100
100 ==> 1000
101 ==> 1000
12345678 ==> 100000000
123456789012345678 ==> 1000000000000000000
1234567890123456789 ==> -8446744073709551616

你想四舍五入到一个重要数字吗?试试。。。更喜欢使用
double
,很明显,我们只需要使用
pow(10.0,ceil(log10(value)))
-不太值得编辑答案,但我想我会添加一个注释不需要
double
但是,是的,我认为这是作者想要的,而不是我发布的,我只是把伪代码作为一个想法。现在它应该正确编译C++(我忘了,C++实际上在数学中确实有10个对数)。不像我想的那么容易,我怀疑我会发现:)谢谢!有些功劳归于@Tommy——我忘了math.h中的
floorf
log10f
函数。但我很高兴我能帮上忙:)我也谢谢你,汤米!你们当中有谁知道如何改进题目吗?恐怕没有一个有同样问题的人会找到这个解决办法。。。