syntax/logic errors

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • abrown07
    New Member
    • Jan 2010
    • 27

    syntax/logic errors

    What are the syntax/logic errors in this code? I am confused between the two types.

    [code]

    int i;
    double pi;

    pi = 1.0;

    for (i=2; i<n, i=i+1)
    {
    if (i%2 = 1)
    pi = pi - (1.0 / ((2.0*i)+1));
    else
    pi = pi + (1.0 / ((2.0*i)+1));
    }

    pi = pi * 4.0;


    [code]/*



    also how can I make the output more accurate?
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    Code:
    int i;
    double pi;
    pi = 1.0;
    for (i=2; i<n, i=i+1)//; missing  n? not declared
    {
    if (i%2 = 1)                              // == equality operator required
       pi = pi - (1.0 / ((2.0*i)+1));  
      else
       pi = pi + (1.0 / ((2.0*i)+1));
    }
    pi = pi * 4.0;

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      A syntax error is a violation of the C language standard; it triggers a compiler error. A logic error is a violation of what you want the program to do.

      The most significant logic error is that you don't have any comments describing what this code snippet is supposed to do. Without a clear statement of your intentions it is difficult to say whether the code accomplishes them.

      It looks like you are using a partial geometric series to approximate the value of pi. If so, the second term is missing and all terms except the first have the wrong sign.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        I think your intention is to approximate the value of pi by evaluating the series
        pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ...
        (I was mistaken in my earlier post to characterize this as a geometric series.)

        There are other techniques that are more efficient (ie, converge faster in fewer iterations). Take a look at Numerical approximations of pi in Wikipedia or do a google search.

        Comment

        Working...