0

excepted output : 1/4,1/2,3/4,1,5/4,3/2 but my output is coming as in the decimal form . Please help how to print in the form of fraction only.

import java.util.*;
public class Hello {

public static void main(String[] args) {
    //Your Code Here
    Scanner s=new Scanner(System.in);
    int n=s.nextInt();
    double d=1/4.0,sum=0;
    for(int i=0;i<n;i++) {
        sum+=d;
        System.out.print(sum+" ");
    }

}}
ave4496
  • 2,950
  • 3
  • 21
  • 48

3 Answers3

1
public class NewClass {

    public static void main(String[] args) {
        System.out.println(convertype(0.75));
    }
    public static String convertype(double decimal){
      int digitsAfterPoint = String.valueOf(decimal).length() - String.valueOf(decimal).indexOf('.')+1; // get the count of digits after the point // for example 0.75 has two digits
      BigInteger numerator  = BigInteger.valueOf((long)(decimal*Math.pow(10, digitsAfterPoint))); // multiply 0.75 with 10^2 to get 75
      BigInteger denominator = BigInteger.valueOf((long)(Math.pow(10, digitsAfterPoint)));       // 10^2 is your denominator
      int gcd = numerator.gcd(denominator).intValue();                                           // calculate the greatest common divisor of numerator  and denominator
      if (gcd > 1 ){                                                                             // gcd(75,100) = 25
        return String.valueOf(numerator.intValue()/gcd) +" / "  + String.valueOf(denominator.intValue()/gcd);  // return 75/25 / 100/25 = 3/4
      }
      else{
        return String.valueOf(numerator) +" / "  + String.valueOf(denominator);              // if gcd = 1 which means nothing to simplify just return numerator / denominator  
      }      
    }
}
Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
1

take input in form of string so it will take input in required format and split it by "/" i.e someString.spit("/"). after that make one for loop and take two number and in two different variable store it. and then take division for both and print it by using "/" in between them.

Ravi
  • 338
  • 1
  • 12
-1

Wrote a method where you can convert double numbers to fraction. Use this to convert it and print as below,

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        int n=s.nextInt();
        double d=1/4.0,sum=0;
        for(int i=0;i<n;i++) {
            sum+=d;
            System.out.print(toFraction(sum)+" ");
        }

    }

    static String toFraction(double x) {
        int w = (int) x;
        int n = (int) (x * 64) % 64;
        int a = n & -n;
        return n == 0 ? w+"" : (w * (64 / a) + (n / a)) + "/" + 64 / a;
    }
}
Sandeepa
  • 3,457
  • 5
  • 25
  • 41