码迷,mamicode.com
首页 > 其他好文 > 详细

C和指针 第十六章 习题

时间:2016-09-16 14:11:00      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:

16.8 计算平均年龄

#include <stdlib.h>
#include <stdio.h>
#define MAX_LEN 512

int main()
{
    int age;
    int totalAge;
    float avgAge;
    int peopleNum;
    FILE *file;
    char info[MAX_LEN];
    char *infoPtr;
    file = fopen("D:/family.txt", "r");

    //按行读取文件
    while(fgets(info, MAX_LEN, file)){
        infoPtr = info;
        peopleNum = 0;
        totalAge = 0;
        //strtol转换字符到数字
        while((age = strtol(infoPtr, &infoPtr, 10)) > 0){
            totalAge += age;
            peopleNum++;
        }
        //类型转换为float,然后计算平均年龄
        avgAge = (float)totalAge / peopleNum;
        printf("%savg: %5.2f\n", info, avgAge);
    }

    return 0;
}

运行:

技术分享

16.9 计算相同生日概率

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

//比较元素
int compare(void const *birth1, void const *birth2){
    return *(int  *)(birth1) - *(int*)(birth2);
}

//打印数组
void print_arr(int *array, int len){
    int idx = 0;
    while(idx <= len){
        printf("%d ", array[idx]);
        idx++;
    }
}

//数组中是否有两个相同数
int count_same(int *array, int len){
    int same = 0;
    while(len > 0){
        if(array[len] == array[len - 1]){
            return 1;
        }
        len--;
    }
    return 0;
}
int main()
{
    int times = 0;
    int randBirthday[30];
    int peopleCount;
    int sameCount = 0;
    srand((unsigned int)time(0));

    while(times < 100000){
        peopleCount = 29;
        while(peopleCount >= 0){
            randBirthday[peopleCount] = rand() % 365;
            peopleCount--;
        }
        qsort(randBirthday, 30, sizeof(int), compare);
        sameCount += count_same(randBirthday, 29);
        times++;
    }
    printf("%f", (float)(sameCount) / 100000);
    return 0;
}

运行:

技术分享

16.10 插入排序

 

C和指针 第十六章 习题

标签:

原文地址:http://www.cnblogs.com/yangxunwu1992/p/5876278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!