newbieprogrammer
newbieprogrammer

Reputation: 868

Maths calculation in java Fraction

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);

     }

 }

Upvotes: 0

Views: 6908

Answers (4)

NominSim
NominSim

Reputation: 8511

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);

Upvotes: 3

Captain GouLash
Captain GouLash

Reputation: 1287

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

double dval=Double.parseDouble(value);

Upvotes: 0

Edo Post
Edo Post

Reputation: 727

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)

Upvotes: 0

Jean Logeart
Jean Logeart

Reputation: 53809

You need to convert your numbers to double:

double temp = ((double) n1) / n2;

Upvotes: 4

Related Questions