root <- function(){
x = as.numeric(readline("please input the number"))
if (x<0){
cat("The number you input is illegal","\n")
root()
}
else{
epsilon = 0.001
numGusses = 1
low = 0
if(x>1){
high = x
}
else{
high = 1
}
ans = (high+low)/2
while(abs(ans*ans-x)>epsilon){
numGusses = numGusses+1
if(ans*ans < x){
low=ans
}
else{
high = ans
}
ans = (high+low)/2.0
}
cat("numGuesses = ",numGusses,"\n")
cat (ans , "is close to square root of", x ,"\n")
}
}
时间: 2024-11-11 18:24:37