What would the syntax be to make a fraction, for example if I wanted to make a program that takes a fraction and adds it to another fraction. I am talking about mathematical fractions btw.
Asked
Active
Viewed 7,788 times
2 Answers
2
You need to create sort of own custom representation of data,
public class Fraction {
private int num;
private int denom;
Fraction(int n,int d){
num = n;
denom = d;
}
Fraction sum(Fraction f1,Fraction f2){
int dtemp = f1.denom*f2.denom;
int ntemp = f1.num*f2.denom+f1.denom*f2.num;
return new Fraction(ntemp,dtemp);
}
Fraction minus(Fraction f1,Fraction f2){
int dtemp = f1.denom*f2.denom;
int ntemp = f1.num*f2.denom-f1.denom*f2.num;
return new Fraction(ntemp,dtemp);
}
Fraction product(Fraction f1,Fraction f2){
return new Fraction(f1.num*f2.num,f1.denom*f2.denom);
}
Fraction divide(Fraction f1,Fraction f2){
return new Fraction(f1.num*f2.denom,f1.denom*f2.num);
}
void printfrac(Fraction fr){
System.out.println("Numerator:"+fr.num+"\t Denominator:"+fr.denom);
}
public static void main(String[] args) {
Fraction f1 = new Fraction(2, 3);
Fraction f2 = new Fraction(1, 2);
System.out.println("Add:\n");
f1.printfrac(f1.sum(f1,f2));
System.out.println("Minus:\n");
f1.printfrac(f1.minus(f1,f2));
System.out.println("Divide:\n");
f1.printfrac(f1.divide(f1,f2));
}
}
OUTPUT:
Add:
Numerator:7 Denominator:6
Minus:
Numerator:1 Denominator:6
Divide:
Numerator:4 Denominator:3

Pankaj Sejwal
- 1,605
- 1
- 18
- 27
0
You need to create a class that is a wrapper for fractions. For member variables you would want integers Numerator and Denominator. You would need methods for adding, subtracting, multiplying, and dividing the fractions with each other.

BoldAsLove
- 660
- 4
- 13
-
Ok, thanks. I didn't realize I have to create a wrapper to do fractions. – Sotark Feb 11 '15 at 05:26