朋友给的练习题,本以为简单,但不成想需要考虑的条件多多:
function divider(dividend,divisor,decimal=0){
if(divisor == 0){//除数不能为0
throw new Error('divisor should not be 0')
}
if(decimal < 0 || parseInt(decimal) != decimal){//精确度只能为正整数
throw new Error('decimal should be a positive int')
}
//判断最终结果是负数还是正数
let isResultPositive = true
if(dividend * divisor > 0){
isResultPositive = true
}else{
isResultPositive = false
}
dividend = Math.abs(dividend)
divisor = Math.abs(divisor)
//整数部分的除法
function intDivider(dividend,divisor){
let i = 0
for(i; dividend - (divisor * i) >= divisor; i++){
}
let quoten = i
return quoten
}
//10的阶乘,为小数部分的除法做准备
function power10 (pow){
let num = 1
for(let i=0;i<pow;i++){
num *= 10
}
return num
}
//如果被整除了,那么加几个精确度0,为能整除的小数部分准备
function add0WhenNoRemainder(decimal){
if(decimal == 0){
return ''
}
let float0 = '.0'
for(let i = 1;i<decimal;i++){
float0 += '0'
}
return float0
}
//小数部分的除法
function remainderDivider(remainder,divisor,decimal){
if(remainder !=0){//如果不能被整除,则按需保留小数后decimal位
let enlarge = power10(decimal)//将余数按“保留几位小数的decimal”放大再除
let quoten = intDivider(remainder * enlarge, divisor)
return '.' + quoten
}else{//如果能被整除,则直接按保留小数后decimal位添加0,如.0000
return add0WhenNoRemainder(decimal)
}
}
//拼接整数部分和小数部分的结果
let intPart = intDivider(dividend,divisor)//整数部分
let remainder = dividend - divisor * intPart
let floatPart = remainderDivider(remainder,divisor,decimal)//小数部分
// console.log(floatPart)
let result = intPart + floatPart
if(!isResultPositive){
result = '-' + result
}
return result
}
let result1 = divider(9,5,2)//1.80
let result2 = divider(-9,5,3)//-1.800
let result3 = divider(9,3,5)//3.00000
let result4 = divider(-9,3,4)//-30000
let result5 = divider(9,7,1)//1.2
console.log(result1,result2,result3,result4,result5)