问题
hi i'm doing a java activity that will divide the two given numbers without using the "/" operator. I want to use a loop statement.
System.out.print("Enter Divident: ");
int ans1 = Integer.parseInt(in.readLine());
System.out.print("Enter Divisor: ");
int ans2 = Integer.parseInt(in.readLine());
The output is:
Enter Dividend: 25
Enter Divisor 5
5
How can solve this without using this "ans1/ans2"
回答1:
if you really want to use loop to divide two numbers, you can write it like code below
int c=0;
while(ans1 >= ans2){
ans1 -= ans2;
c++;
}
after loop c
equals quotient and ans1
equals reminder of division
if abs1
and abs2
are signed numbers, below code should be work for division
boolean n1 = (ans1 & (1<<31))!=0;
boolean n2 = (ans2 & (1<<31))!=0;
ans1 = Math.abs(ans1);
ans2 = Math.abs(ans2);
int c=0;
while(ans1 >= ans2){
ans1 -= ans2;
c++;
}
if(!n1 && n2) c = -c;
else if(n1 && !n2){
c = -c;
if(ans1 > 0){
ans1 = ans2 - ans1;
c--;
}
}else if(n1 && n2){
if(ans1 > 0){
ans1 = ans2 - ans1;
c++;
}
}
回答2:
Using recursion:
// Calculate: a / b
public int divide (int a, int b) {
if ( a < b ) {
return 0;
} else {
return 1 + divide ( a - b, b );
}
}
回答3:
If you really want to do it without the / operator and im guessing probably without shifting either the simplest loop method would be to count the number of times you need to subtract ans2 from ans1 without the remainder going below ans1.
Pseudo code:
numtimes init at 0
counter init at ans1
while counter is greater than ans2
subtract ans2 from counter
numtimes increase by 1
check numtimes
回答4:
BigInteger do the trick witout /
operator, literally.
(new BigInteger(ans1 + "")).divide(new BigInteger(ans2 + ""))
回答5:
You can do it in the following way:
System.out.print("Enter Divident: ");
int ans1 = Integer.parseInt(in.readLine());
System.out.print("Enter Divisor: ");
int ans2 = Integer.parseInt(in.readLine());
int count=0;
while(ans1>=ans2)
{
ans1=ans1-ans2;
count++;
}
System.out.println(count);
回答6:
Something like below ?
int i=1;
int mul;
while(true)
{
mul = i++;
if(mul*(ans2)==ans1)
{
System.out.println(mul);
break;
}
else if(mul*(ans2)>ans1)
{
System.out.println("Cannot be divided");
break;
}
}
来源:https://stackoverflow.com/questions/12740750/dividing-an-two-number-using-loop-statement