Montecarlo 方法和 JFrame数学和 Java 问题

问题描述

我做了一个小程序来近似 Pi,我想代表它。我开始了,但我认为如果圆圈外面的点是红色的,里面的点是绿色的,那会更好看。我做不到,我不明白为什么会出现问题。不知道是纯数学还是开发。

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main() {
    int *weights,n = 0,i;
    double sum = 0;

    FILE* fp = fopen("elephant_seal_data.txt","rb");
    if (!fp)
        exit(1);
    fscanf(fp,"%d\n",&n);
    weights = malloc(n * sizeof(int));
    for (i = 0; i < n; ++i)
        fscanf(fp,"%d",&weights[i]);
    for (i = 0; i < n; ++i)
        sum += weights[i];
    printf("average is %.2f\n",sum / n);
    fclose(fp);
    free(weights); // don't forget to free the memory!
}

如果有人能帮我,那就完美了。

解决方法

可以用更简单的方式完成。

for (int i = 0; i < 1000; i++) {
    double x = Math.random();
    double y = Math.random();
    double applyformula = (x * x) + (y * y);

    if (applyformula <= 1) {
        g.setColor(Color.GREEN);
    } else {
        g.setColor(Color.RED);
    }
    // Set the actual coordinates in a 250 pixels wide square.
    x *= 250;
    y *= 250;
    g.fillOval((int) x,(int) y,5,5);
}