C语言怎么产生30-100的随机数?

C语言怎么产生30-100的随机数?,第1张

利用C提供的伪随机数产生函数rand实现。为了获得“逼真随机”效果,随机数产生前应当用当前时间值调用库函数srand来设定伪随机数产生器的初始值(常称下种子)。rand函数默认生成0~32767的随机数,为达到题设30~100的要求,要将由rand生成的随机数对71取模处理来获得0~70的范围,然后再+30便得到题解。代码如下(以产生100个0~70的范围随机数为例):

#include "stdio.h"

#include "stdlib.h"//调用srand和rand需包含此文件

#include "time.h"//调用time需包含此文件

int main(int argc,char *argv[]){

int n,l

srand((unsigned)time(NULL))//调用库函数sran为伪随机产生器下种子

for(l=n=0n<100n++)

printf(++l%15 ? "%4d" : "%4d\n",rand()%71+30)//由rand()%71+30获得30~100的范围

if(l%15)

printf("\n")

return 0

}

运行样例如下:

Option Base 1

Option Explicit

Dim a(11) As Integer

Private Sub Command1_Click()

Dim i As Integer

Picture1.Cls

Picture1.Print "产生的一维数组为:"

Randomize

For i = 1 To 10

a(i) = Int(Rnd * 20 + 10)

Picture1.Print a(i)

Next i

Picture1.Print

End Sub

Private Sub Command2_Click()

Dim max As Integer, p As Integer, i As Integer

For i = 1 To 10

If max <a(i) Then max = a(i)

Next

Picture1.Print "最大值为:" &max

End Sub

Private Sub Command3_Click()

Dim p As Integer, i As Integer, sum As Integer

For i = 1 To 10

sum = sum + a(i)

Next

Picture1.Print "平均值为:" &CStr(sum / 10)

End Sub

Private Sub Command4_Click()

Dim i As Integer, m As Integer, b(10) As Integer, j As Integer

For i = 1 To 10

b(i) = a(i)

Next i

For i = 10 To 1 Step -1

For j = 1 To i - 1

If b(j) >b(j + 1) Then

m = b(j + 1)

b(j + 1) = b(j)

b(j) = m

End If

Next j

Next i

Picture1.Print "数组按从大到小排序:"

For i = 1 To 10

Picture1.Print b(i)

Next

End Sub

Private Sub Command5_Click()

Dim x%, p%, i%

x = Val(InputBox("输入要插入的数据:"))

p = 1

Do While x >a(p) And p <= 10

p = p + 1

Loop

For i = 10 To p Step -1

a(i + 1) = a(i)

Next i

a(p) = x

Picture1.Print

Picture1.Print "插入后的一维数组为:"

For i = 1 To 11

Picture1.Print a(i)

Next i

End Sub

#include<stdio.h>

#include<time.h>

#include<stdlib.h>

void func1(int arr[])//随机生成30个1~100间的整数

void func2(int arr[])//求最大值

void func3(int arr[])//求最小值

void func4(int arr[])//求平均值

void func1(int arr[]){

int i=0

srand((unsigned)time(NULL))

for(i=0i<30i++){

arr[i]=rand()%100+1

}

printf("这些数分别是:\n")

for(i=0i<30i++){

printf("%d\t",arr[i])

if((i+1)%5==0){printf("\n")}//五个换一行

}

printf("\n")

}

void func2(int arr[]){

int i=0,max=-1

for(i=0i<30i++){

if(arr[i]>max){max=arr[i]}

}

printf("最大值为:%d\n",max)

}

void func3(int arr[]){

int i=0,min=101

for(i=0i<30i++){

if(arr[i]<min){min=arr[i]}

}

printf("最小值为:%d\n",min)

}

void func4(int arr[]){

int i=0,sum=0

for(i=0i<30i++){

sum+=arr[i]

}

printf("平均值为:%.2f\n",sum/30.0)

}

int main(){

int arr[30]

func1(arr)

func2(arr)

func3(arr)

func4(arr)

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/9436235.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-28
下一篇 2023-04-28

发表评论

登录后才能评论

评论列表(0条)

保存