Logarithm computing without math.h

匿名 (未验证) 提交于 2019-12-03 08:52:47

问题:

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 variable i becomes equal N + 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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!