Strange behaviour of var

Tobias Brandt tob.brandt at googlemail.com
Thu Nov 10 12:14:36 PST 2011


'hits' and 'n' are both integers and hits < n, therefore hits/n = 0
in integer arithmetic.
You need to convert at least one of them to a floating point type,
e.g., with 'cast(double)(hits)/n'.

On 10 November 2011 21:08, Fabian <talk2fab at online.de> wrote:
> Hey guys,
>
> I've got a problem - I've just written a few lines to approximate PI with the
> Monte Carlo Method.
>
> This is my code:
>
> import std.stdio, std.conv, std.string, std.random;
>
> void main()
> {
>        string buf;
>        int n, hits;
>        float x, y, pi;
>
>        Random rnd;
>        rnd.seed(unpredictableSeed);
>
>        write("Please enter the number of approximation steps: ");
>        stdin.readln(buf);
>        buf = chomp(buf);
>
>        if(isNumeric(buf))
>        {
>                n = parse!int(buf);
>                for(int i = 0; i <= n -1; i++)
>                {
>                        x = uniform(0.0f, 1.0f, rnd);
>                        y = uniform(0.0f, 1.0f, rnd);
>
>                        if((x*x + y*y) <= 1)
>                        {
>                                hits++;
>                                writeln(hits);  //only for debugging
>                        }
>                }
>
>                pi = (hits / n) * 4.f;
>                writeln(pi);
>        }
> }
>
> But the result is always 0 because my var "hits" is set to zero before I try
> to calculate PI. But why? Please help me.
>
> Nice wishes
> Fabian
>


More information about the Digitalmars-d-learn mailing list