我正在尝试制作自定义 pow() 函数,但我的 for 循环不起作用 - C
I am trying to make a custom pow() function but my for loops are not working - C
我正在尝试制作自定义 pow() 函数来比较实际 pow 函数的结果,但它不起作用。当基数为 1 时,它工作正常,但之后 MyPower 函数将 return 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++){
调试程序的一点小建议
这可能看起来很老套,但是尝试 运行 用笔和纸来检查您的算法将有助于您发现此类错误。毫无疑问,随着您获得更多经验,您会变得越来越熟练。欢迎使用 Whosebug!
我正在尝试制作自定义 pow() 函数来比较实际 pow 函数的结果,但它不起作用。当基数为 1 时,它工作正常,但之后 MyPower 函数将 return 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++){
调试程序的一点小建议
这可能看起来很老套,但是尝试 运行 用笔和纸来检查您的算法将有助于您发现此类错误。毫无疑问,随着您获得更多经验,您会变得越来越熟练。欢迎使用 Whosebug!