drand48()在我的c程序中不起作用

时间:2017-03-24 17:35:55

标签: c random posix

由于某些原因,我的drand48()都没有返回0-1之间的随机数,就像它们应该... x只导致输入的数字为n,而y保持为0

/// Challenge: Darts
/// circle of radius 0.5 inside a 2x2 square
/// throw darts (x) times and calculate random hits

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

int main() {
  double n, t, z, a;
  int x, y;

  printf("How many darts do you want to throw? ");
  scanf("%lf", &n);
  printf("Okay, let's throw %lf darts\n. . .\n", n);

  z = 0;
  a = 0;
  t = 0;

  while (t <= n) {
    x = drand48(); /// returns # 0-1
    x = x - 0.5; /// puts it on a graph with domain/range -0.5 - 0.5
    y = drand48();
    y = y - 0.5;

    if ((((x^2) + (y^2))^2) <= 0.25) {
      z = z + 1;
    }
    t = t + 1;
  }
  a = z / (t - 1);
  printf("%lf\n", a);
}

/// remember to compile with gcc darts.c -lm
/// remember to run with ./a.out

0 个答案:

没有答案