我试图用蒙特卡罗方法计算pi。但我总是零,我不知道为什么。 这是我的代码
#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");
}
答案 0 :(得分:4)
answer
计算中的整数除法:
answer = n / N;
'努夫说。
编辑1:
现在是星期五,所以我会补充一些解释。
变量n
和N
被声明为整数。
该分部优先于任何转换或分配。除法作为两个整数执行,然后小数部分被截断。其余值将转换为double
,然后分配给变量answer
。
请不要根据具体情况区分标识符。 n
和N
应该是不同的字母。这有助于作者和审稿人避免拼写错误。