Strange behaviour of var
    Fabian 
    talk2fab at online.de
       
    Thu Nov 10 12:08:25 PST 2011
    
    
  
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