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 插入排序
时间: 2024-10-11 01:15:33