When I input two negative numbers in my program that finds the LCM and HCF of a number, the HCF returns 0. It works fine for positive numbers. Here is the code for HCF module. What can I do to fix it?
static int hcf(int x, int y){
int hcf = 0;
for (int i = x; i>=1; i--){
if (y%i==0 && x%i==0){
hcf = i;
break;
}
}
return hcf;
}
If x
is less or equal to 0, i
will be initialized with x
value and the for
loop won't execute anything due to the condition i >= 1
, thus the method will return 0.
Probably you should try to initialize i
to (int)Math.abs(x)
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句