My task is to accept 2 fractions and sum them and then return in the simplest form.
For some reason the line "gcd = i;"does not run while executing and hence my program enters an infinite loop when I run it.
import java.util.*;
class fraction {
public static void main(String[] args) {
int num1, den1, num2, den2;
Scanner sc = new Scanner(System.in);
/* System.out.print("Enter first numerator:");
num1 = sc.nextInt();
System.out.print("Enter first denominator:");
den1 = sc.nextInt();
System.out.print("Enter second numerator:");
num2 = sc.nextInt();
System.out.print("Enter second denominator:");
den2 = sc.nextInt(); */
num1 = 1;
den1 = 2;
num2 = 1;
den2 = 2;
System.out.print(num1 + "/" + den1 + " + " + num2 + "/" + den2 + " is equal to ");
int num = num1 * den2 + den1 * num2;
int dum = den1 + den2;
System.out.println(num + "/" + dum);
System.out.println(num % dum);
int gcd = 2;
while (num % dum == 0) {
for (int i = 1; i < num && i < dum; ++i) {
if (num % i == 0 && dum % i == 0) {
gcd = i;//This line.
System.out.println(gcd + " " + i);
}
}
num = num / gcd;
dum = dum / gcd;
}
System.out.println(num + "/" + dum);
}
}
You always enter in gcd = i;
the problem is that at the end of the statement you have
num1 1
den1 2
num2 1
den2 2
num 2
dum 2
gcd 1
so num = num/gcd
returns 2 and also dum = dum/gcd
= 2. So you cannot go out of the while cycle
Maybe you can solve in the for cycle putting for (i =2... )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.