我正在尝试创建一个自定义 pow() 函数来比较实际 pow 函数的结果,但它不起作用。当底数为 1 时,它工作正常,但之后 MyPower 函数将返回 1 的任何一次幂,所以它会说。
测试 1.000000 的 1 次方
测试 1.000000 的 2 次方
测试 1.000000 的 3 次方
测试 1.000000 的 4 次方
2.000000 转 1 为 2.000000,结果为 1.000000
2.000000 转 2 为 4.000000,结果为 2.000000
2.000000 转 3 为 8.000000,结果为 4.000000
2.000000 到 4 是 16.000000,结果是 8.000000
对于所有其余的基数,它将继续减少一个指数值。我相信错误发生在 MyPower() 函数中,但我不确定。
#include <stdio.h>
#include <math.h>
double base, x;
int exponent, i, z;
double MyPower(double base, int exponent);
void DoTest(double base, int exponent);
double MyPower(double base, int exponent){
double x = 1;
for(z = 1; z < exponent; z++){
x *= base;
}
return x;
}
int main(void){
int i, j;
for(i = 1; i < 5; i++){
for(j = 1; j < 5; j++){
DoTest(i,j);
}
}
}
void DoTest(double base, int exponent){
double test1 = MyPower(base, exponent);
double pow_result = pow(base, exponent);
if(test1 == pow_result){
printf("Testing %f to the %d power\n", base, exponent);
}
else{
printf("%f to the %d is %f, result is %f\n", base, exponent, pow_result, test1);
}
}
最佳答案
问题来自循环中的条件。
您赋予 z 的初始值和退出条件的组合使其比您想要执行的迭代少一次:
for(z = 1; z < exponent; z++){
x *= base;
}
您需要将其更改为:
for(z = 0; z < exponent; z++){
或者:
for(z = 1; z <= exponent; z++){
调试程序时的一点建议
这可能看起来很过时,但尝试用笔和纸运行算法将帮助您发现此类错误。毫无疑问,随着经验的增加,你会变得越来越熟练。欢迎来到 StackOverflow!
关于c - 我正在尝试制作自定义 pow() 函数,但我的 for 循环不起作用 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58072205/