Thread: Having trouble with aproximating pi in c

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    1

    Having trouble with aproximating pi in c

    so basically I have to use Madhava‐Leibniz series in the approximation of pi but I have to use it in a loop. But Im stuck at with an error "invalid operands to binary %". Here my code so far...


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
            double x,y,q,k;
            x = 4;
            y = 1;
            
           
    
    	for (k = 0;k = 0;k--) 
        {
            
          	
    	    
            if (y%2 = 0)
            {
                    q = q + x / y;
                    printf("%f\n", q);
        
            }  
                          
            else if (y%2 > 0)
            {
                 q = q - x / y;
                    printf("%f\n", q);
            }
                 
    	
    	
    	
    	}
    
       
            
    
     system("pause");
    
     return(0);   
    }
    I'm dont know why the operand is invalid.

  2. #2
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    The modulo operator % can't be applied to floats / doubles.

  3. #3
    Registered User
    Join Date
    Apr 2011
    Posts
    1
    if (y%2 = 0) <- incorrect.

    if (y % 2 == 0) <- correct

  4. #4
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    This is wrong:
    for (k = 0;k = 0;k--)
    You did not initialize q.
    You are not updating y anywhere. You should make y an int so that the modulo stuff works.

  5. #5
    THANK YOU KINDLY SIR Phenax's Avatar
    Join Date
    Mar 2011
    Posts
    74
    If you want to do a modulo with a fractional numerator or denominator, try using fmod from math.h. The % operator is for integers only.
    Quote Originally Posted by Plato
    Never discourage anyone...who continually makes progress, no matter how slow.

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Shortest lived for loop, ever:
    for (k = 0;k = 0;k--)


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pi - Hm, somethign is not right here.
    By MadnessRed in forum C++ Programming
    Replies: 8
    Last Post: 09-12-2008, 01:07 PM
  2. Pi Calculation
    By EvilGuru in forum C Programming
    Replies: 2
    Last Post: 05-02-2005, 04:25 AM
  3. Pi and the standard library
    By FOOTOO in forum C Programming
    Replies: 7
    Last Post: 04-15-2005, 11:23 AM
  4. menu selection trouble
    By Spectrum48k in forum C Programming
    Replies: 13
    Last Post: 11-20-2002, 11:06 PM
  5. C for PI
    By Lynux-Penguin in forum C Programming
    Replies: 13
    Last Post: 04-28-2002, 07:37 PM