Advertisement
Guest User

Untitled

a guest
Dec 17th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. /**
  2. * Rational.java
  3. * The purpose of this class is to print out rational numbers and find the gct if possible
  4. *
  5. * @author Cameron Lee
  6. * @version 11/13/2018
  7. */
  8.  
  9. public class Rational
  10. {
  11. private int numerator;
  12. private int denominator;
  13.  
  14. public Rational(int numerator, int denominator)
  15. {
  16. this.numerator = numerator;
  17. this.denominator = denominator;
  18. }
  19.  
  20. public double getRationalAsDouble()
  21. {
  22. return(this.numerator/(double)this.denominator);
  23. }
  24.  
  25. public void reduce()
  26. {
  27. // Finds the greatest common denominator
  28. int gcd = 1;
  29. for(int i = 1; i <= this.numerator && i <= this.denominator; i++)
  30. {
  31. // Checks to see if i can be factored from both numerator and denominator
  32. if(this.numerator % i == 0 && this.denominator % i == 0)
  33. {
  34. gcd = i;
  35. }
  36. }
  37.  
  38. this.numerator = this.numerator/gcd;
  39. this.denominator = this.denominator/gcd;
  40. }
  41.  
  42. public void addRational(Rational rational)
  43. {
  44. // Creates new denominator
  45. int a = this.denominator * rational.denominator;
  46.  
  47. // Creates new numerator
  48. int b = this.numerator * rational.denominator;
  49. int c = this.denominator * rational.numerator;
  50.  
  51. this.numerator = b + c;
  52. this.denominator = a;
  53.  
  54. // Reduces the number
  55. this.reduce();
  56.  
  57. }
  58.  
  59. public static void main(String[] args)
  60. {
  61. Rational half = new Rational(2, 4);
  62. Rational third = new Rational(3, 9);
  63. Rational fourth = new Rational(12, 48);
  64.  
  65. System.out.println(half.numerator + "/" + half.denominator);
  66. System.out.println("+");
  67. System.out.println(third.numerator + "/" + third.denominator);
  68. System.out.println("=");
  69.  
  70. half.addRational(third);
  71.  
  72. System.out.println(half.numerator + "/" + half.denominator);
  73.  
  74. System.out.println("");
  75.  
  76. System.out.println(fourth.numerator + "/" + fourth.denominator);
  77. System.out.println("=");
  78.  
  79. fourth.reduce();
  80.  
  81. System.out.println(fourth.numerator + "/" + fourth.denominator);
  82.  
  83. }
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement