分数计算在编程中通常通过定义分数类或函数来实现,核心步骤包括分子分母运算、化简分数等。以下是不同编程语言的实现示例:
一、Java实现(使用类和辅助函数)
```java
import java.util.Scanner;
public class FractionCalculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n1, d1, n2, d2, op;
char o;
int n, d;
System.out.println("Enter fraction 1 (numerator/denominator): ");
n1 = in.nextInt(); d1 = in.nextInt();
System.out.println("Enter operator (+, -, *, /): ");
o = in.next().charAt(0);
System.out.println("Enter fraction 2 (numerator/denominator): ");
n2 = in.nextInt(); d2 = in.nextInt();
Fraction result;
switch(o) {
case '+':
result = new Fraction(n1 * d2 + n2 * d1, d1 * d2);
break;
case '-':
result = new Fraction(n1 * d2 - n2 * d1, d1 * d2);
break;
case '*':
result = new Fraction(n1 * n2, d1 * d2);
break;
case '/':
result = new Fraction(n1 * d2, d1 * n2);
break;
default:
System.out.println("Invalid operator");
return;
}
System.out.println(result);
}
}
class Fraction {
int num, den;
public Fraction(int num, int den) {
this.num = num;
this.den = den;
simplify();
}
private void simplify() {
int gcd = gcd(Math.abs(num), Math.abs(den));
num /= gcd;
den /= gcd;
if (den < 0) {
num = -num;
den = -den;
}
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
```
二、Python实现(使用类)
```python
from math import gcd
class Fraction:
def __init__(self, num, den):
self.num = int(num)
self.den = int(den)
self.simplify()
def simplify(self):
common = gcd(abs(self.num), abs(self.den))
self.num //= common
self.den //= common
if self.den < 0:
self.num = -self.num
self.den = -self.den
def __add__(self, other):
new_num = self.num * other.den + other.num * self.den
new_den = self.den * other.den
return Fraction(new_num, new_den)
def __sub__(self, other):
new_num = self.num * other.den - other.num * self.den
new_den = self.den * other.den
return Fraction(new_num, new_den)
def __str__(self):
return f"{self.num}/{self.den}"
示例使用
f1 = Fraction(1, 2)
f2 = Fraction(3, 4)
print(f1 + f2) 输出 5/4
```
三、C语言实现(通过函数)
```c
include include int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } void simplify(int *num, int *den) { int common = gcd(abs(*num), abs(*den)); *num /= common; *den /= common; if (*den < 0) { *num = -*num; *den = -*den; } } int main() { int n, op, a, b, c, d, x, y, t; scanf("%d", &n); while (n--) { scanf("%d%d%d%d%d", &op, &a, &b, &c, &d); int x, y; switch(op) { case 1: x = a * d + b * c; y = b * d; break; case 2: x = a * d - b * c; y = b * d; break; case 3: x = a * d; y = b * c; break; case 4: x = a * d; y = b * c; break; default: printf("Invalid operatorn"); return 1; } simplify(&x, &y); printf("%d/%dn", x, y); } return 0