C语言中约简形式的N个分数的乘积
给定N个分数的分子num和分母den,任务是找到N个分数的乘积,并且输出结果应为约简形式。
例如,在下图中,我们有两个分数“4/5”和“3/4”,我们找到了这两个分数的乘积,其中第一个分数的分子乘以第二个分数的分子,第一个分数的分母乘以第二个分数的分母。现在的最终结果是“12/20”,可以约简,所以输出应该是“3/5”,同样,我们必须开发一个程序来解决给定的问题。

输入
fraction f[3] = {{1,2},
{2,1},
{5,6}}输出
5/6
说明 − 1/2 * 2/1 * 5/6 = 10/12,可以约简为 5/6。
输入
fraction f[2] = {{2, 3},
{1,4}}输出
1/6
说明 − 2/3 * 1/4 = 2/12,可以约简为 1/6
下面使用的解决问题的方法如下
为了解决上述问题,我们可以将所有分母和分子相乘,将结果存储在另一个变量prod_den和prod_num中,它们将分别成为最终分母和最终分子,现在我们必须找到约简形式,为此我们必须找到prod_num和prod_den的GCD(最大公约数),并用它们各自的GCD除以prod_num和prod_den。
算法
Start
Declare a struct fraction with following elements
1. num, 2. den
In function int GCD(int a, int b)
Step 1→ If a == 0 then,
Return b
Step 2→ Return GCD(b % a, a)
In function int product(int n, fraction f[])
Step 1→ Initialize prod_num = 1 prod_den = 1
Step 2→ Loop For i = 0; i < n; i++
prod_num = prod_num * f[i].num
prod_den = prod_den * f[i].den
Step 3→ Declare and initialize gcd = GCD(prod_num, prod_den)
Step 4→ prod_num = prod_num / gcd
Step 5→ prod_den = prod_den / gcd
Step 6→ Print prod_num, prod_den
In Function int main()
Step 1→ Declare struct fraction f[3] = {
{1,2},
{2,1},
{5,6}}
Step 2→ Declare and initialization n as sizeof(f)/sizeof(f[0])
Step 3→ product(n, f)
Stop示例
#include <stdio.h>
struct fraction{
int num;
int den;
};
// Function to return gcd of a and b
int GCD(int a, int b){
if (a == 0)
return b;
return GCD(b % a, a);
}
//fucntion to print the result
int product(int n, fraction f[]){
int prod_num = 1, prod_den = 1;
// finding the product of all N
// numerators and denominators.
for (int i = 0; i < n; i++) {
prod_num *= f[i].num;
prod_den *= f[i].den;
}
// Finding GCD of new numerator and
// denominator
int gcd = GCD(prod_num, prod_den);
// finding reduced form
prod_num /= gcd;
prod_den /= gcd;
printf("%d/%d
", prod_num, prod_den);
return 0;
}
int main(){
struct fraction f[3] = {
{1,2},
{2,1},
{5,6}};
int n = sizeof(f)/sizeof(f[0]);
product(n, f);
return 0;
}输出
如果运行上述代码,它将生成以下输出:
5/6
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP