0

I am trying to implement a basic calculation. The program take in 2 numbers, it works fine with 10 divided by 5 and give answer 2. If any smaller value divided by a larger value it will give me 0, can I have the answer in fraction?

Example 8 divided by 100 equal 8/100 rather than 0.

 public class numtheory {

     public static void main(String[] args) {

         int n1;
         int n2;
         Scanner scan = new Scanner(System. in );
         System.out.println("input number 1: ");
         n1 = scan.nextInt();
         System.out.println("input number 2: ");
         n2 = scan.nextInt();
         int temp1 = n1 / n2;
         System.out.print("\n Output :\n");
         System.out.print(temp1);
         System.exit(0);

     }

 }
Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126
newbieprogrammer
  • 848
  • 7
  • 23
  • 46
  • See: http://stackoverflow.com/questions/474535/best-way-to-represent-a-fraction-in-java?rq=1 – Justin Apr 25 '13 at 17:37

4 Answers4

4

You need to convert your numbers to double:

double temp = ((double) n1) / n2;
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • 1
    This gives him the result as a decimal, he wants to output as fraction. – NominSim Apr 25 '13 at 16:46
  • Not sure of that: if he wants to output the fraction, he better not compute any calculation and output n1 + "/" + n2. And I don't think that's the question... – Jean Logeart Apr 25 '13 at 16:49
  • @newbieprogrammer you just have `int` and `double` (and others) primitive types to represent numbers. If you want/need a fraction interpretation of a `double`, you will need to implement it by yourself or use a third party library but since you're in learning phase you just have to stick to `double`. – Luiggi Mendoza Apr 25 '13 at 16:50
  • i have search though the forum but none show how to output as fraction =( – newbieprogrammer Apr 25 '13 at 16:53
  • @Vakh Judging from the OPs comments he does want to output as a fraction. Perhaps you could edit your answer to reflect that. – NominSim Apr 25 '13 at 17:36
3

If you want to produce a fraction, you can just print out:

System.out.println(n1 + "/" + n2);

This will print out whatever numbers you're given though, they won't be reduced. You can reduce them yourself however with something like:

int n = n1;
int d = n2;

while (d != 0) {
    int t = d;
    d = n % d;
    n = t;
}

int gcd = n;

n1 /= gcd;
n2 /= gcd;

And then print them out:

System.out.println(n1 + "/" + n2);
NominSim
  • 8,447
  • 3
  • 28
  • 38
0

Instead of using integers, you need to use double. This because an integer can only contain while numbers where double can contain decimal numbers.

u could change all the int to double or cast the in to double by dooing

((double) yourIntValue)
Edo Post
  • 727
  • 7
  • 18
0

you could also get the input as a string, and parse it with

double dval=Double.parseDouble(value);
Captain GouLash
  • 1,257
  • 3
  • 20
  • 33