第8章 数组

练习题:

8.2.1  用rand函数生成[10, 20]之间的随机整数,表达式应该怎么写?

   答案: rand()%11 +10

8.3.1 补完本节直方图程序的main函数,以可视化的形式打印直方图。例如上一节统计20个随机数的结果是:

  code:

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

#define MAX_LEN 20
char randomData[MAX_LEN] = {0};
int data_num[10] = {0};
int max_num=0x00;

//产生0~9随机数
void gen_randon(void)
{
    int i;
    srand(time(NULL));
    for(i=0; i<MAX_LEN; i++){
        randomData[i] = rand() % 10;
    }
}

//打印产生的随机数数组
void print_random_data(void)
{
    int i;
    printf("the random data is:\n");
    for(i=0x00; i<MAX_LEN; i++){
        if(i!=0 && i%10 ==0)
            printf("\n");
        printf("%d ", randomData[i]);
    }
    printf("\n");    
}

//计算0~9随机数出现的次数
void count_num(void)
{
    int i;
    for(i=0; i<MAX_LEN; i++){
        data_num[randomData[i]]++;
    }
    printf("the num count is:\n");
    for(i=0x00; i<10; i++){
        printf("%d ", data_num[i]);
    }
    printf("\n");
}

//求取0~9随机数出现的最大次数
void get_max_num(void)
{
    int i;
    for(i=0x00; i<10; i++){
        if(data_num[i] > max_num)
            max_num = data_num[i];
    }
    printf("the max_num = %d\n", max_num);
}

//打印0~9随机数的次数显示柱状图
void print_histogram(void)
{
    int i, j;
    for(i=0x00; i<10; i++){
        printf("%d ", i);
    }
    printf("\n");
    for(i=0x01; i<=max_num; i++){
        for(j=0x00; j<10; j++){
            if(data_num[j] >= i){
                printf("* ");
            }else{
                printf("  ");
            }
        }
        printf("\n");
    }
}

int main(int argc, char *agrv[])
{
    gen_randon();
    print_random_data();
    count_num();
    get_max_num();
    print_histogram();
}

 

  运行结果:

例子:

例8.5 剪刀石头布游戏

code:

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

int main(int argc, char *argv[])
{
    char gesture[3][10] = {"scissor", "stone", "cloth"};
    int man, computer;
    int ret, result;
    while(1){
        printf("\ngame start, please input your gesture:\n(0-scissor, 1-stone, 2-cloth)\n");
        ret = scanf("%d", &man);
        if(ret==-1 || man > 2 || man<0){
            printf("Invalid input!\n");
            return 1;
        }
        srand(time(NULL));
        computer = rand() % 3;
        printf("You: %s\tcomputer: %s\n", gesture[man], gesture[computer]);
        result = (man-computer+4) % 3 - 1;
        if(result > 0)
            printf("You win!\n");
        else if(result == 0)
            printf("Draw!\n");
        else
            printf("You lose!\n");
    }
    return 0;
}

结果截图:

posted @ 2019-05-27 11:08  shanyu20  阅读(283)  评论(0编辑  收藏  举报