C primer plus (第六版)第十二章 编程练习第6题

题目:

6.编写⼀个程序,⽣成1000个1〜10范围内的随机数。不⽤保存或打印这些数字,仅打印每个数出现的次数。⽤10个不同的种⼦值运⾏,⽣成的数字出现的次数是否相同?可以使⽤本章⾃定义的函数或ANSI C的rand()和srand()函数,它们的格式相同。这是⼀个测试特定随机数⽣成器随机性的⽅法。

思路:

  1. 参考12章中程序清单12.9中的例子,手动输入种子数值并生成随机数的示例中的函数,输入一个数,重置种子数,然后生成需要的随机数;

  2. 存储这10随机数作为后续1000个随机数生成的种子数;

  3. 用calloc()函数建立10个整数存储空间(malloc()函数无法对建立的存储控制置0),每生成一个1~10范围的随机数,便对相应空间内的计数+1;

代码:

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>

int rand1(void);                    //随机数生成函数
void srand1(unsigned int seed);     //重置种子数,为了符合题意需要10个不同的种子数
unsigned long int next = 1;         

int main()
{
    unsigned int seed;
    unsigned int seed_qty = 10;         //设置随机生成的种子的数量是10个
    unsigned int seed_ar[seed_qty];     //设置10个随机生成的种子存储在数组中
    unsigned int * count_pt; 
    //用count_pt来统计最后生成的1~10范围内的整数的个数
    count_pt = calloc(10, sizeof(unsigned int)); //不用malloc是因为无法对初始化的内存位置0

    printf("Please enter your choice for seed.\n"); //这里设置需要用户先输入一个数用以后续10个随机数种子的种子数
    while (scanf("%u", &seed) == 1)
    {
        srand1(seed);    /* 重置种⼦ */
        break;
    }

    for (int i = 0; i < seed_qty; i++)      //回测生成的10个随机数种子,防止问题
        seed_ar[i] = rand1();

    puts("the random seed numbers:");       //回测生成的10个随机数种子,防止问题
    for (int i = 0; i < seed_qty; i++)
    {
        printf("seed %d = %d\n",i+1, seed_ar[i]);
    }
    
    for (int i = 0; i < seed_qty; i++)      //将10个随机种子依次用一遍
    {
        srand1(seed_ar[i]);                 //随机函数重置种子
        for ( int j = 0; j < 100; j++)      //每个随机数种子生成100个随机数
        {
            unsigned int temp;
            temp = rand1()%10 + 1;          //temp的值是生成的1~10之内的随机数,
            // printf("%d\n",temp);
            count_pt[temp-1] = count_pt[temp-1] + 1;    //count_pt[temp-1]是需要累加计数数组
            // printf("%d\n",count_pt[temp-1]);
        }
    }
    
    for (int i = 0; i < seed_qty; i++)      //回测显示1~10的随机数出现次数
    {
        printf("number %5d show %5d times\n",i+1, count_pt[i]);
    }

    free(count_pt);
    return 0;
}

int rand1(void)
{
    /*⽣成伪随机数的魔术公式*/
    extern unsigned long int next;
    next = next * 1103515245 + 12345;
    return (unsigned int) (next / 65536) % 32768;
}

void srand1(unsigned int seed)
{
    extern unsigned long int next;
    next = seed;
}
相关推荐
十月的皮皮1 小时前
stm20260720-从新手 C 到量产 STM32 工程:程序设计推导指南
c语言·开发语言·stm32·stm32cubemx·hal库
Echo缘2 小时前
嵌入式系统C语言资源分类与内存分布分析
c语言·开发语言
chexus6 小时前
20. 深入 Nginx 信号处理
linux·c语言·网络·nginx
代码雕刻家7 小时前
编程语法细节
java·c语言·开发语言
草莓熊Lotso7 小时前
【Linux网络】深入理解Linux IO多路复用:从本质到select服务器实战
linux·运维·服务器·c语言·网络·数据库·c++
Discipline~Hai1 天前
ARM01-ARM体系架构
linux·c语言·arm开发·架构
cjr_xyi1 天前
AT1202Contest_c binarydigit 题解
c语言·c++·算法
Navigator_Z1 天前
LeetCode //C - 1156. Swap For Longest Repeated Character Substring
c语言·算法·leetcode
无相求码1 天前
const vs #define:C语言常量定义的差异
c语言·算法
Android洋芋1 天前
AI辅助C盘清理
c语言·开发语言·人工智能·ai辅助c盘清理