以下c++问题解决不了,请大神指导,请尽量详细注释和思路。谢谢!
1、写名为MyRealNothNo的函数,它不带任何参数,并在范围[1, 100 ]中返回一个随机整数。
2、编写一个C++主程序,在范围[1, 100 ]中重复地生成和打印随机整数。当连续打印值之间的差值的绝对值小于5时,程序必须停止。
在编写主程序时,必须使用部分(1)中定义的MyRealNo函数。在编写主程序时,必须提供所有必需的includes和命名空间。
如以下两个示例输出:
1。程序可以输出:76 43,77,94,54,41,45
2。程序可以输出:42 40
#include "time.h"
#include "stdlib.h"
#include <iostream>
using namespace std;
int MyRealNothNo()
{
return rand() % 100 + 1; //一个任意数,除以100取余数,肯定是[0,99],+1就是[1,99]
}
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsigned)time(NULL)); //初始化随机数种子
int x = MyRealNothNo(), y;
while (y = MyRealNothNo())
{
cout << x << " ";
if (x - y < 5 && x - y > -5) break; //判断绝对值<5
x = y;
}
cout << y << endl;
return 0;
}
不同意下面这种传统的随机数生成方式
srand((unsigned)time(NULL)); //初始化随机数种子
他的局限是time(NULL) 受系统时间以秒为单位,当计算比较快的时候种子一样,可能会导致生成的随机数为同一数值。
因此建议采用记时精度更高的作为种子数,比如CPU的tick计数
@caozhy 朋友,我想说的并不是这个问题,我将这种代码的潜在风险模拟出来,你可以看下处理结果!
#include "time.h"
#include "stdlib.h"
#include <iostream>
using namespace std;
int MyRealNothNo()
{
return rand() % 100 + 1; //一个任意数,除以100取余数,肯定是[0,99],+1就是[1,99]
}
void yours()
{
srand((unsigned)time(NULL)); //初始化随机数种子
int x = MyRealNothNo(), y;
while (y = MyRealNothNo())
{
cout << x << " ";
if (x - y < 5 && x - y > -5) break; //判断绝对值<5
x = y;
}
cout << y << endl;
return;
}
int _tmain(int argc, _TCHAR* argv[])
{
for (int i = 0; i < 100; i++)
yours();
return 0;
}