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"); }
nandNare integers, so when you divide them, it's done as integer math. Sincenis always less than or equal toN, the answer will always be 0. You then multiply by4.0, which produces adouble, but by then it's too late -- 0 * 4.0 is still 0.