gpt4 book ai didi

c - 将随机生成的数字存储在变量中

转载 作者:太空宇宙 更新时间:2023-11-03 23:34:17 25 4
gpt4 key购买 nike

我正在尝试编写一个计算数学方程式的程序,但我对如何生成从 0.00 到 1.00 的随机数并将其存储在变量 a 中感到困惑。

到目前为止,这是我的代码,我坚持现在如何获取该数字并将其存储以备将来使用。我需要将该随机数存储在 a 中,然后在循环中使用它,然后生成一个新的随机数并在循环的第二个循环中使用它。

编辑这就是我现在一直在做的,假设计算一个随机数在区域内的次数,计数,然后除以运行的次数,但我没有得到任何输出

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

void initrand(void)
{
srand(time(0));
}

float randfloat(void)
{
return rand()/(float)RAND_MAX;
}



int main(void)
{
int n = 10;
float x;
float y;
float pi = 3.1415;
float rootxy;
initrand();
int z = 0;
int inside = 0;
x = randfloat();
y = randfloat();
float area = 0.25 * pi;
float calculatedpi;
rootxy = sqrt(pow(x,2) + (pow(y,2)));

while (z < n){
if (rootxy > area) {
inside++;
z++;
}
else{
return 0;
}
calculatedpi = (inside/n);
}


printf("%f", calculatedpi);

最佳答案

您的代码存在一些问题:

  • 你不应该使用嵌套函数。一些编译器支持它们作为扩展,但它不是标准的。在main
  • 之外定义 randfloatinitrand
  • initrand 函数做得太少了。为什么不从 main 调用 srand((time(0));
  • 您的 initrand 函数被声明为返回 double 值,但它不返回任何内容(并且它的命名方式不应该)。如果你需要使用这样的函数,为什么不让它返回 void 呢?
  • 您应该很少使用float。为什么不使用 double

也就是说,您可以这样做来存储该随机值:

double randdouble() 
{
return rand()/((double)RAND_MAX + 1);
}

int main()
{
double x = randdouble();
/* ... */
}

关于c - 将随机生成的数字存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8023075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com