使用循环语句划分两个数字 [英] Dividing an Two number Using Loop Statement
本文介绍了使用循环语句划分两个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做一个java活动,它将分割两个给定的数字而不使用/运算符。我想使用循环语句。
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());
输出为:
Enter Dividend: 25
Enter Divisor 5
5
如果你真的想用loop来划分两个数字,如何解决这个问题而不使用这个ans1 / ans2
How can solve this without using this "ans1/ans2"
推荐答案
,你可以写下面的代码
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++;
}
循环后 c
等于商和 ans1
等于除法提醒
after loop c
equals quotient and ans1
equals reminder of division
如果 abs1
和 abs2
是签名号码,下面的代码应该适用于分部
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++;
}
}
这篇关于使用循环语句划分两个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文