我需要把一个数字乘以10到(x)幂,这取决于我可能需要的指数。我知道在<math.h>库中有一个函数,但我想知道我是否可以使自己的函数实现基本相同的功能,但只用于10,而不是任何数字。这是当然的家庭作业,但由于我们还没有被告知这个库,我想尝试实现它没有说的power()功能。
这是我的代码;它确实编译了,但是我得到了一些奇怪的数字,而不是预期的5000。
#include <cs50.h>
#include <stdio.h>
int ten_to_the(int n);
int main(void) {
int x = 50;
x *= ten_to_the(2);
printf("%.i\n", x);
}
int ten_to_the(int n) {
n = 1;
for (int i = 0; i < n; i++) {
n *= 10;
}
return n;
}发布于 2022-10-25 06:18:03
因为在循环的每一次迭代中,您将n乘以10,所以i < n永远不会成为真。在实践中,n一直在变大,直到溢出并变为负值。
使用另一个变量来跟踪结果,将其与需要计算的迭代次数分开。
而不是这样:
int ten_to_the(int n)
{
n = 1;
for (int i = 0; i < n; i++)
{
n *= 10;
}
return n;
}这是:
int ten_to_the(int n)
{
int result = 1;
for (int i = 0; i < n; i++)
{
result *= 10;
}
return result;
}https://stackoverflow.com/questions/74189726
复制相似问题