#include <stdio.h>
#include <math.h>
int main()
{
int loop, place_value=0, c = 5;
for(loop = 0; loop < c; loop++)
{
place_value = 0;
place_value = pow(10, loop);
printf("%d \n", place_value);
}
return 0;
}这段代码给出了
10
99
1000
9999 为什么第三行和第五行是99和9999,而不是100和10000?
当正常请求电源时,它会给出正确的答案。
#include <stdio.h>
#include <math.h>
int main()
{
printf ("%d", (int) pow (10,3 ));
return 0;
}1000发布于 2021-02-06 00:24:43
pow是一个很难实现的例程,并且并不是所有的实现都能给出好的结果。粗略地说,pow(x, y)的核心算法是从x (一部分)计算一个对数,将其乘以y,然后在乘积上计算一个指数函数。在浮点中这样做会引入难以控制的舍入误差。
结果是pow(10, 4)的计算结果可能接近10,000,但略小于或大于10,000。如果小于,则将其转换为整数生成9999。
当您在源代码中使用硬编码的参数时,编译器可能会在编译期间计算答案,可能会使用不同的算法。例如,当y是3时,它可以像在x*x*x中那样简单地将第一个参数乘以第一个参数,而不是使用对数指数算法。
至于为什么您测试的奇数会出现低结果,请考虑将5.45454545乘以10的各种幂并四舍五入为整数时会发生什么。5.45454545个四舍五入为5。54.5454545个四舍五入为55。545.454545下舍入为545.向上或向下舍入是小数点外的分数的结果。对于使用pow(10, loop)的情况,10的对数的位可能恰好给出您尝试的几个奇数的这种模式。
发布于 2021-02-06 00:43:49
pow(x, y)函数或多或少地转换为exp(log(x) * y),这将给出一个与x^ y不完全相同的结果。
为了解决这个问题,你可以这样做:
round(pow(x, y))发布于 2021-02-06 01:17:56
经验法则:永远不要使用带整数的浮点函数(特别是像pow或log这样的复杂函数)。
简单地实现整数次幂
unsigned intpow(unsigned x)
{
unsigned result = 1;
while(x --) result *= 10;
return result;
}它会快得多,甚至(最快的)
int intpow1(unsigned x)
{
const static unsigned vals[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, /* ... */};
#if defined(CHECK_OVERFLOW)
if(x >= sizeof(vals)/ sizeof(vals[0])) return -1;
#endif
return vals[x];
}https://stackoverflow.com/questions/66066756
复制相似问题