编写函数实现分数约分 c语言代码
时间: 2024-02-11 21:34:32 浏览: 43
以下是一个简单的 C 语言函数,用于将分数约分为最简形式:
```c
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
void reduce_fraction(int *numerator, int *denominator) {
int divisor = gcd(*numerator, *denominator);
*numerator = *numerator / divisor;
*denominator = *denominator / divisor;
}
int main() {
int numerator = 4;
int denominator = 8;
reduce_fraction(&numerator, &denominator);
printf("%d/%d\n", numerator, denominator);
return 0;
}
```
该函数接受两个指针参数:分子和分母。它使用递归算法计算它们的最大公约数并将其用于约分。最后,它在控制台输出约分后的结果。
相关问题
C语言编写函数实现统计全班某门功课期末考试的平均分数和最高分
可以编写如下的C语言函数实现统计全班某门功课期末考试的平均分数和最高分:
```c
#include <stdio.h>
void calcScore(int scores[], int len, float *avg, int *max) {
int sum = 0;
*max = scores[0];
for (int i = 0; i < len; i++) {
sum += scores[i];
if (scores[i] > *max) {
*max = scores[i];
}
}
*avg = (float)sum / len;
}
int main() {
int scores[] = {80, 90, 85, 70, 95, 75, 88, 92, 79, 83};
int len = sizeof(scores) / sizeof(int);
float avg;
int max;
calcScore(scores, len, &avg, &max);
printf("平均分数为:%.2f,最高分为:%d\n", avg, max);
return 0;
}
```
这个函数的参数包括:
- `scores`:一个整型数组,存储全班某门功课期末考试的分数;
- `len`:整数,表示数组 `scores` 的长度;
- `avg`:指向浮点数的指针,用于存储平均分数;
- `max`:指向整数的指针,用于存储最高分数。
函数首先使用一个循环遍历数组 `scores`,累加所有的分数,并找出最高分数。然后,计算平均分数,并将结果存储到指针 `avg` 指向的变量中,将最高分数存储到指针 `max` 指向的变量中。最后,主函数中调用这个函数,获取平均分数和最高分数,并打印输出。
c语言编写函数对结构体类型数据进行排序
C语言编写函数对结构体类型数据进行排序的方法有很多种。下面给出一种常见的实现方法。
首先,定义一个包含多个成员的结构体类型,例如学生信息结构体Student,其中包含成员name(姓名)、age(年龄)和score(分数)。
接下来,编写一个排序函数sort,该函数接受一个Student类型的数组和数组大小作为参数。在排序过程中,可以使用常见的排序算法,比如冒泡排序、快速排序、插入排序等。这里以冒泡排序为例演示排序过程。
```c
#include <stdio.h>
#include <string.h>
// 定义学生信息结构体类型
typedef struct {
char name[100];
int age;
float score;
} Student;
// 排序函数
void sort(Student arr[], int size) {
int i, j;
Student temp;
for(i = 0; i < size - 1; i++) {
for(j = 0; j < size - 1 - i; j++) {
// 使用strcmp函数比较字符串大小
if(strcmp(arr[j].name, arr[j + 1].name) > 0) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
Student students[] = {
{"Alice", 18, 89.5},
{"Bob", 20, 77.8},
{"Cathy", 19, 95.3}
};
int size = sizeof(students) / sizeof(students[0]);
sort(students, size);
for(int i = 0; i < size; i++) {
printf("name: %s, age: %d, score: %.1f\n", students[i].name, students[i].age, students[i].score);
}
return 0;
}
```
运行该程序,输出结果为:
```
name: Alice, age: 18, score: 89.5
name: Bob, age: 20, score: 77.8
name: Cathy, age: 19, score: 95.3
```
以上就是使用C语言编写函数对结构体类型数据进行排序的一个示例。通过定义自定义的结构体类型和使用合适的排序算法,可以实现对结构体类型数据的排序。