0

I'm trying to calculate the pi using Monte Carlo Method. But I always get zero, I don't know why. Here's my code

 #include <tchar.h> #include <Windows.h> #include <omp.h> #include <iostream> #include<math.h> using namespace std; int main(int argc, char *argv[]){ int N = 1000, n = 0; double x = 0, y = 0; double answer; for (int i = 0; i < N; i++){ x = (double)rand() / (double)RAND_MAX; y = (double)rand() / (double)RAND_MAX; if (((x*x) + (y*y)) < 1) ++n; } //cout << "n = " <<n << endl; answer = n / N; cout << answer*4.0 << endl; //system("pause"); } 
1
  • 4
    Both n and N are integers, so when you divide them, it's done as integer math. Since n is always less than or equal to N, the answer will always be 0. You then multiply by 4.0, which produces a double, but by then it's too late -- 0 * 4.0 is still 0. Commented Feb 27, 2015 at 21:51

1 Answer 1

4

Integer division in the answer calculation:

answer = n / N; 

'nuff said.

Edit 1:
It's Friday, so I'll add some explanation.

The variables n and N are declared as integers.

The division takes precedence over any conversions or assignments. The division is performed as two integers, then the fractional portion is truncated. The remaining value is converted to double then assigned to the variable answer.

Please, please, don't differentiate identifiers by case. The n and N should be different letters. This helps the writer and reviewer refrain from typo defects.

Sign up to request clarification or add additional context in comments.

1 Comment

@JerryCoffin: Thanks. Must be a Friday thing. :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.