分数计算器c++程序代码
时间: 2023-05-16 19:01:36 浏览: 191
分数计算器C是一种大家都常用的小型软件,主要功能是支持分数的四则运算和求最大公约数。以下是一份分数计算器C的程序代码:
#include <stdio.h>
#include <stdlib.h>
// 分数结构体
typedef struct Fraction{
int numerator; // 分子
int denominator; // 分母
}Fraction;
// 求最大公约数
int gcd(int a, int b){
return b == 0 ? a : gcd(b, a % b);
}
// 约分
Fraction reduce(Fraction f){
if(f.numerator == 0){ // 如果分子为0,分母置为1
f.denominator = 1;
}else{
int d = gcd(abs(f.numerator), abs(f.denominator));
f.numerator /= d;
f.denominator /= d;
}
return f;
}
// 加法
Fraction add(Fraction f1, Fraction f2){
Fraction sum;
sum.numerator = f1.numerator * f2.denominator + f2.numerator * f1.denominator;
sum.denominator = f1.denominator * f2.denominator;
return reduce(sum);
}
// 减法
Fraction substract(Fraction f1, Fraction f2){
Fraction diff;
diff.numerator = f1.numerator * f2.denominator - f2.numerator * f1.denominator;
diff.denominator = f1.denominator * f2.denominator;
return reduce(diff);
}
// 乘法
Fraction multiply(Fraction f1, Fraction f2){
Fraction product;
product.numerator = f1.numerator * f2.numerator;
product.denominator = f1.denominator * f2.denominator;
return reduce(product);
}
// 除法
Fraction divide(Fraction f1, Fraction f2){
Fraction quotient;
quotient.numerator = f1.numerator * f2.denominator;
quotient.denominator = f1.denominator * f2.numerator;
return reduce(quotient);
}
int main(){
Fraction f1 = {1, 2};
Fraction f2 = {2, 3};
// 加法
Fraction f3 = add(f1, f2);
printf("%d/%d + %d/%d = %d/%d\n", f1.numerator, f1.denominator, f2.numerator, f2.denominator, f3.numerator, f3.denominator);
// 减法
Fraction f4 = substract(f1, f2);
printf("%d/%d - %d/%d = %d/%d\n", f1.numerator, f1.denominator, f2.numerator, f2.denominator, f4.numerator, f4.denominator);
// 乘法
Fraction f5 = multiply(f1, f2);
printf("%d/%d * %d/%d = %d/%d\n", f1.numerator, f1.denominator, f2.numerator, f2.denominator, f5.numerator, f5.denominator);
// 除法
Fraction f6 = divide(f1, f2);
printf("%d/%d ÷ %d/%d = %d/%d\n", f1.numerator, f1.denominator, f2.numerator, f2.denominator, f6.numerator, f6.denominator);
return 0;
}
以上是分数计算器C的程序代码,通过运行该程序可以实现分数的加减乘除运算,并且支持自动约分和求最大公约数功能。
阅读全文