假设有结构体定义如下,编程对分数进行约减。格式如下。输入提示:"please input a fraction,for example:16/24"输入格式:"%d%d"输出格式:"%d%d\n"
时间: 2023-09-23 20:13:26 浏览: 76
下面是可能的实现代码:
```c
#include <stdio.h>
// 定义分数结构体
struct Fraction {
int numerator; // 分子
int denominator; // 分母
};
// 求最大公约数
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
// 约分函数
struct Fraction reduce(struct Fraction f) {
int divisor = gcd(f.numerator, f.denominator);
f.numerator /= divisor;
f.denominator /= divisor;
return f;
}
int main() {
struct Fraction f;
printf("please input a fraction,for example:16/24\n");
scanf("%d/%d", &f.numerator, &f.denominator);
f = reduce(f);
printf("%d/%d\n", f.numerator, f.denominator);
return 0;
}
```
其中,`reduce` 函数用于约分,它接受一个分数结构体,返回约分后的结果。`gcd` 函数用于求最大公约数,采用递归实现。在 `main` 函数中,先提示用户输入一个分数,然后读入分子和分母,接着调用 `reduce` 函数进行约分,并打印约分后的结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)