fork download
  1. import java.io.*;
  2. import java.util.*;
  3. class Ideone {
  4. public static void main(String[] args) {
  5. Scanner scan = new Scanner(System.in);
  6. String exp=scan.nextLine(); //System.out.println(exp);
  7. int campuran=-1,pecahan=-1, desimal=-1;
  8. for(int i=0; i<exp.length(); i++) { //System.out.println(exp.substring(i,i+1));
  9. if(exp.substring(i,i+1).equals(" ")) campuran=i;
  10. if(exp.substring(i,i+1).equals("/")) pecahan=i;
  11. if(exp.substring(i,i+1).equals(".")) desimal=i;
  12. } //System.out.printf("%d %d\n",campuran, pecahan);
  13. if(campuran>-1) {
  14. int x = Integer.parseInt(exp.substring(0,campuran));
  15. int y = Integer.parseInt(exp.substring(campuran+1,pecahan));
  16. int z = Integer.parseInt(exp.substring(pecahan+1,exp.length()));
  17. int gcd = gcd(y,z);
  18. y/=gcd;
  19. z/=gcd;
  20. double hasil = (double) x+(double)y/z;
  21. System.out.println("Desimal: " + hasil);
  22. System.out.printf("Pecahan campuran: %d %d/%d\n",x, y, z);
  23. System.out.printf("Pecahan: %d/%d\n", x*z+y, z);
  24. } else if(pecahan>-1) {
  25. int y = Integer.parseInt(exp.substring(0,pecahan));
  26. int z = Integer.parseInt(exp.substring(pecahan+1,exp.length()));
  27. int gcd = gcd(y,z);
  28. y/=gcd;
  29. z/=gcd;
  30. double hasil = (double)y/z;
  31. System.out.println("Desimal: " + hasil);
  32. if(y%z==0) {
  33. System.out.println("Pecahan campuran: " + hasil);
  34. System.out.println("Pecahan: " + hasil);
  35. } else {
  36. if(y/z==0) System.out.printf("Pecahan campuran: %d/%d\n", y%z, z);
  37. else System.out.printf("Pecahan campuran: %d %d/%d\n", y/z, y%z, z);
  38. System.out.printf("Pecahan: %d/%d\n", y%z, z);
  39. }
  40. } else if(desimal>-1) {
  41. double x= Double.parseDouble(exp);
  42. int y = Integer.parseInt(exp.substring(0,desimal));
  43. int z = Integer.parseInt(exp.substring(desimal+1,exp.length()));
  44. int numerator = Integer.parseInt(exp.substring(0,desimal)+exp.substring(desimal+1,exp.length()));
  45. int denominator = (int) Math.pow(10, exp.length()-desimal-1); //System.out.println(numerator + " " + denominator);
  46. int gcd = gcd(numerator, denominator);
  47. numerator /= gcd;
  48. denominator /= gcd;
  49. System.out.println("Desimal: " + x);
  50. if (numerator / denominator == 0) System.out.printf("Pecahan campuran: %d/%d\n", numerator, denominator);
  51. else System.out.printf("Pecahan campuran: %d %d/%d\n", numerator / denominator, numerator % denominator,denominator);
  52. System.out.printf("Pecahan: %d/%d\n", numerator, denominator);
  53. } else {
  54. System.out.println("Desimal: 0");
  55. System.out.println("Pecahan campuran: 0");
  56. System.out.println("Pecahan: 0");
  57. }
  58. }
  59. static int gcd (int a, int b) {
  60. if(b==0) return a;
  61. else return gcd(b, a%b);
  62. }
  63. }
  64.  
Success #stdin #stdout 0.16s 58980KB
stdin
30 3/6
stdout
Desimal: 30.5
Pecahan campuran: 30 1/2
Pecahan: 61/2