Question

I'm trying to write a Quasi- Monte Carlo Approximation of pi in C. I am not well versed in it yet and am trying to translate my python based skills, so I may be simply overlooking something. I keep getting 0 as a result and I can't figure out why. How should I fix this? Also, I get an error on the last two printf calls saying they are type double * and not double. It compiles anyways, is this related?

#include <stdio.h>
/*  
Tristen Wentling
montepithon.c
October 31, 2013

*/  
int main(void)
{   
    float i,j,x;
    float count=0,counter=0;
    printf("Please enter the desired grid division size (n=?)");
    scanf("%f", &x);
    float y=x*x;
    if(x==0){
        printf("goodbye");
    }   
    else if(x!=0){
        for(i=0;i<=x;i++){
            for(j=0;j<=x;j++){
                float check=((i*i)*(1/y))+((j*j)*(1/y));
                /*printf("%f\n", check);*/
                if(check<=1){
                    count+=1;
                }   
                else{
                    counter+=1;
                }   
            }   
        }   
    }   
    else{
        printf("error");
    }   
    float prsum=count/y;
    float ptsum=(1-counter)*(1/y);
    double pirprox=4*prsum;
    double pitprox=4*ptsum;
    printf("%f\n", &pirprox);
    printf("%f\n", &pitprox);
    getchar();
}   
Was it helpful?

Solution

%f format specifier in printf expects double type argument. &pirprox and &pitprox is of type double * and you cannot print an address with %f. Wrong format specifier would invoke undefined behavior.
Change your code snippet

 printf("%f\n", &pirprox);

 printf("%f\n", &pitprox);  

to

 printf("%f\n", pirprox);

 printf("%f\n", pitprox);  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top