转载_srand()以及rand()函数用法(zz)

本文详细介绍了C语言中rand()和srand()函数的工作原理及应用技巧,探讨了如何利用时间戳作为种子来提高随机数生成的质量,并给出了具体的代码示例。

srand()就是给rand()提供种子seed

如果srand每次输入的数值是一样的,那么每次运行产生的随机数也是一样的,

srand(n)

for(10)

rand()
也就是说,以一个固定的数值作为种子是一个缺点。 通常的做法是  以这样一句代码srand((unsigned) time(NULL));来取代,这样将使得种子为一个不固定的数, 这样产生的随机数就不会每次执行都一样了。


1,先看一个例子
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main( void )
{
int i;
/* Seed the random-number generator with current time so that
* the numbers will be different every time we run.
*/
srand( (unsigned)time( NULL ) );
/* Display 10 numbers. */
for( i = 0; i < 10;i++ )
printf( " %6d/n", rand() );
}

2.关于time.h
time.h中包含很多有趣的函数,譬如
char *ctime(long *clock)
本函数把clock所指的时间(如由函数time返回的时间)转换成下列格式的
字符串:Mon Nov 21 11:31:54 1983/n/0

#i nclude <iostream>
#i nclude <stdlib.h>
#i nclude <time.h>
using namespace std;


void main()
{
time_t t1,t2;
char getTime[20];
char *ptstring=getTime;

int x,count=0;
x=RAND_MAX;
cout<<<'/n';
t1=time(NULL);
ptstring=ctime(&t1);

while(count<=100)
{
srand( (unsigned)time( NULL ) );
x=rand()%50;
if(x<5)
continue;
else
{
count++;
cout<<"the numth is "<<<'/n';
}
}

查看ptstring的值会显示 "Tue Sep 13 16:31:06 2005"

3, 最后说说srand()函数
void srand(unsigned seed) 初始化随机数发生器

有讨论如下:
1.C的函数库之所以没有把使用系统时钟初始化随机种子这步重要的操作直接放进ran

d函数的实现中,我觉得至少有三个原因:
(1)可以高效产生连续的随机数,不用每次都初始化;
(2)给程序员以更高的灵活性,因为可能在要求较高的场合,应该使用更好的的数据

做种子,而不是系统时钟;
(3)对于只是想产生大量伪随机数来尽兴某种验证或者统计,未必需要初始化,大不

了程序每次运行都产生同样的一系列随机数而已——有些情况下,这是无所谓的。

事实上有一个更重要的原因:
作为伪随机序列产生器的rand()函数,必须具备的一个重要特性就是-》产生的序

列必须是可重现的。
这不仅仅是一个算法,相当大的程度上,它关系到代码测试的准确性。如果算法中

使用了和rand()的结果相关的数据,通过一个可控的可重现序列,我们就有机会再现每一

次测试的过程,从而更有效的找到问题的所在。
所以这里提出一个建议,代码中,如果rand()的函数结果关系到算法的结果,那么

,必须保证你的rand()调用是可重现的。

4,c语言里函数rand()和srand()的用法 - -

rand(void)用于产生一个伪随机unsigned int 整数。
srand(seed)用于给rand()函数设定种子。

srand 和 rand 应该组和使用。一般来说,srand 是对 rand 进行设置。
比如:
srand((UINT)GetCurrentTime());
int x = rand() % 100;
是生成 0 到 100 之间的随机数。

srand()是用来初始化随机种子数的,因为rand的内部实现是用线性同余法做的,他不是真

的随机数,只不过是因为其周期特别长,所以有一定的范围里可看成是随机的,式子如下


rand = rand*const_1 + c_var;
srand函数就是给它的第一个rand值。

用"int x = rand() % 100;"来生成 0 到 100 之间的随机数这种方法是不或取的,
比较好的做法是: j=(int)(n*rand()/(RAND_MAX+1.0))   产生一个0到n之间的随机


RAND_MAX=0x7fffffff

5.总结
1)srand()给rand()提供种子
2)srand()中的seed一般由时间函数得,eg srand((UINT)GetCurrentTime()) srand( (u

nsigned)time( NULL ) ) time()函数得到现在的系统时间...等等

#include <iostream> #include <vector> #include <algorithm> #include <iomanip> #include <ctime> using namespace std; enum ProcessState { READY, RUNNING, FINISHED }; struct PCB { int pid, arrival_time, burst_time, remaining_time, priority, start_time = -1, finish_time = -1; float response_ratio = 0; ProcessState state = READY; PCB(int id, int arrive, int burst, int prio = 0) : pid(id), arrival_time(arrive), burst_time(burst), remaining_time(burst), priority(prio) {} }; vector<PCB> ready_queue, finished_processes; PCB* current_process = nullptr; int system_time = 0, idle_time = 0, time_quantum = 2, remaining_quantum = 2; void addProcess(PCB process) { ready_queue.push_back(process); } void runProcess(bool isRR = false) { if (!current_process) { idle_time++; cout << "系统时间 " << system_time << ": CPU空闲\n"; return; } cout << "进程 " << current_process->pid << " 执行第 " << current_process->burst_time - current_process->remaining_time + 1 << " 秒\n"; current_process->remaining_time--; if (isRR) remaining_quantum--; if (current_process->remaining_time == 0) { current_process->state = FINISHED; current_process->finish_time = system_time + 1; finished_processes.push_back(*current_process); cout << "进程 " << current_process->pid << " 执行完毕,系统时间第 " << system_time + 1 << " 秒\n"; delete current_process; current_process = nullptr; remaining_quantum = time_quantum; } else if (isRR && remaining_quantum == 0) { current_process->state = READY; ready_queue.push_back(*current_process); cout << "进程 " << current_process->pid << " 时间片用完,重新加入就绪队列,系统时间第 " << system_time + 1 << " 秒\n"; delete current_process; current_process = nullptr; remaining_quantum = time_quantum; } } void scheduleProcess(int algorithm) { if (current_process && (algorithm != 3 || (algorithm == 3 && remaining_quantum > 0))) return; auto arrived = [](const PCB& p) { return p.arrival_time <= system_time; }; vector<PCB> arrived_processes; copy_if(ready_queue.begin(), ready_queue.end(), back_inserter(arrived_processes), arrived); if (arrived_processes.empty()) return; switch (algorithm) { case 1: // FCFS sort(arrived_processes.begin(), arrived_processes.end(), [](const PCB& a, const PCB& b) { return a.arrival_time < b.arrival_time; }); break; case 2: // SPN sort(arrived_processes.begin(), arrived_processes.end(), [](const PCB& a, const PCB& b) { return a.remaining_time < b.remaining_time; }); break; case 3: // RR sort(arrived_processes.begin(), arrived_processes.end(), [](const PCB& a, const PCB& b) { return a.arrival_time < b.arrival_time; }); break; case 4: // Priority sort(arrived_processes.begin(), arrived_processes.end(), [](const PCB& a, const PCB& b) { return a.priority > b.priority; }); break; case 5: // HRRN for (auto& p : arrived_processes) p.response_ratio = (system_time - p.arrival_time + p.burst_time) / (float)p.burst_time; sort(arrived_processes.begin(), arrived_processes.end(), [](const PCB& a, const PCB& b) { return a.response_ratio > b.response_ratio; }); break; } auto it = find_if(ready_queue.begin(), ready_queue.end(), [&arrived_processes](const PCB& p) { return p.pid == arrived_processes.front().pid; }); if (it != ready_queue.end()) { current_process = new PCB(*it); ready_queue.erase(it); current_process->state = RUNNING; if (current_process->start_time == -1) current_process->start_time = system_time; cout << "进程 " << current_process->pid << " 开始执行,系统时间第 " << system_time << " 秒\n"; } } void printStatistics() { float total_turnaround = 0, total_weighted = 0; sort(finished_processes.begin(), finished_processes.end(), [](const PCB& a, const PCB& b) { return a.pid < b.pid; }); cout << "\n调度统计信息:\nPID\t到达\t执行\t完成\t周转\t带权周转\n"; for (const auto& p : finished_processes) { int turnaround = p.finish_time - p.arrival_time; float weighted = turnaround / (float)p.burst_time; total_turnaround += turnaround; total_weighted += weighted; cout << p.pid << "\t" << p.arrival_time << "\t" << p.burst_time << "\t" << p.finish_time << "\t" << turnaround << "\t" << fixed << setprecision(2) << weighted << endl; } if (!finished_processes.empty()) { cout << "\n平均周转时间: " << fixed << setprecision(2) << total_turnaround / finished_processes.size() << endl; cout << "平均带权周转时间: " << fixed << setprecision(2) << total_weighted / finished_processes.size() << endl; } cout << "CPU空闲时间: " << idle_time << endl; } vector<PCB> generateProcesses(int n = 5) { vector<PCB> processes; srand(time(nullptr)); for (int i = 1; i <= n; ++i) processes.emplace_back(i, rand() % 5, 1 + rand() % 10, 1 + rand() % 10); return processes; } int main() { auto processes = generateProcesses(); cout << "\n初始进程信息:\nPID\t到达\t执行\t优先级\n"; for (const auto& p : processes) { cout << p.pid << "\t" << p.arrival_time << "\t" << p.burst_time << "\t" << p.priority << endl; addProcess(p); } cout << "\n选择调度算法:\n1.FCFS\n2.SPN\n3.RR\n4.Priority\n5.HRRN\n请输入(1-5): "; int choice; cin >> choice; cout << "\n开始调度...\n"; while (finished_processes.size() < processes.size()) { if (choice == 4) // Priority抢占式处理 { auto highest = max_element(ready_queue.begin(), ready_queue.end(), [](const PCB& a, const PCB& b) { return a.priority < b.priority && a.arrival_time <= system_time; }); if (highest != ready_queue.end() && (current_process == nullptr || highest->priority > current_process->priority)) { if (current_process) { current_process->state = READY; ready_queue.push_back(*current_process); cout << "进程 " << current_process->pid << " 被抢占,系统时间第 " << system_time << " 秒\n"; delete current_process; current_process = nullptr; } } } scheduleProcess(choice); runProcess(choice == 3); system_time++; } printStatistics(); return 0; } 这个代码中时间片轮转调度算法有错误,请改正后把完整的代码发给我
最新发布
06-28
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值