gpt4 book ai didi

c - 在c编程中生成等差数列的随机数

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

这是我现在的代码:

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

int main()
{
float r;

srand((unsigned)time(NULL));

r = (float)rand()/RAND_MAX*20;
printf("%.1f\n",r);


return(0);
}

代码可以生成一个 0 -20 范围内的小数随机数,但我想生成一个像 0.5,1.0,1.5,2.0,2.5...19.5,20.0 这样的数字。

我应该在我的程序中添加什么?

最佳答案

我会将随机数保留为 int 并在 1 到 40 之间生成它。然后除以 2.0 得到你想要的数字。

类似于:

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

int main()
{
float r;
int n;

srand((unsigned)time(NULL));

for (int i=0; i<10; ++i)
{
n = rand() % 40 + 1; // Gives random values 1, 2, …, 39, 40
r = n/2.0; // Divide by floating point 2 to get 0.5, 1.0, .. 20.0
printf("%.1f\n",r);
}

return(0);
}

这应该给你值 0.5、1.0、1.5、…、19.5、20.0

示例输出:

14.0
0.5
11.0
4.5
15.0
8.0
19.5
18.0
19.0
6.0

关于c - 在c编程中生成等差数列的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52557953/

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