问题
I'm trying to compute ln(x) by Taylor series. Here is my code:
#define N 10
float ln(float x){
int i;
float result;
float xt;
float xtpow;
int sign;
if(x > 0 && x <= 1){
xt = x - 1.0;
sign = -1;
xtpow = 1.0;
result = 0;
for(i = 1 ; i < N + 1; i++ );
{
// Problem here
printf("%d\n", i);
sign = sign * (-1);
xtpow *= xt;
result += xtpow * sign / i;
}
}else if(x >= 1)
{
return -1 * ln(1.0 / x);
}
return result;
}
The problem is with my series cycle(see above). It seems like after 1 cycle variable i
becomes equal N + 1
, and nothing going on after it. Have you any ideas why it is so?
回答1:
It seems like after
1
cycle variablei
becomes equalN + 1
remove ;
after for loop:
for(i = 1 ; i < N + 1; i++ );
^
Your loop continue execute without executing code in block you putted in braces { }
after for loop and for loop just increments i
till for loop breaks. After the loop code block (where you commented "problem is here") get executes with i = N + 1
value.
I am not sure but I have an additional doubt about conditional expressions in if()
. You code pattern is something like:
if(x > 0 && x <= 1){ <-- "True for x == 1"
// loop code
}
else if(x >= 1){ <-- "True for x == 1"
// expression code here
}
So for x
== 1
else code never execute. Check this code too.
来源:https://stackoverflow.com/questions/18961889/logarithm-computing-without-math-h