Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C Programming

Name: Anonymous 2012-09-27 14:06

Hi /prog/,
I'm writing a small program in C to calculate the value of pi using the Montecarlo algorithm.
What can I do to improve it ?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

long EVALPI(long);

#ifdef EBUG
#define DEBUG
#endif

/* README:
        you can add -DEBUG to your CFLAGS.
        Usage: ./montecarlo [number of loops] [rand seed]
        If the number of loops is not provided, it'll be asked on the command line.
        If the rand seed is not provided, it'll use the current timestamp using time() (3).
*/

int main(int argc, char **argv){
        long c, p;

        if(argc > 1){
                p = atoi(argv[1]);
        }else{
                printf("Nombre d'iterations: ");
                scanf("%ld", &p);
        }

        if(argc > 2)
                srand(atoi(argv[2]));
        else
                srand(time(NULL));

        c = EVALPI(p);
        printf("pi ~= 4*%ld/%ld ~= %f\n", c, p, (double)(c<<2)/p);
        return 0;
}

long EVALPI(long p){
        const long CENTRE = RAND_MAX >> 1;
        const long CENTRE_2 = CENTRE * CENTRE;
        long x, y, c = 0;
#ifdef DEBUG
        long old = p, foo = p/4;
#endif
        do{
                x = CENTRE - rand();
                x *= x;
                y = CENTRE - rand();
                y *= y;
                if(x+y < CENTRE_2) c++;
#ifdef DEBUG
                if(p % foo == 1) printf("%f\n", (double)(c<<2)/(old-p));
#endif
        }while(p--);

        return c;
}

Name: Anonymous 2012-09-27 21:25

Explain all your code line by line to an inanimate object.
Use a consistent brace style that isn't K&R.
Space out your code more.
Functionally, it's pretty well written, I'd say. But I can't help but think that the code is kinda ugly.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List