两道面试题
1. 编程题
1) 请用js定义一个Animal类,包含属性name以及方法sleep
2) 请定义Person类,继承上面的类,并添加speak方法
function Animal() {
this.name = '';
}
Animal.prototype.sleep = function () { console.log('sleep...'); };
function Person () {}
Person.prototype = new Animal();
Person.prototype.constructor = Person;
Person.prototype.speak = function() { console.log('speak...'); };
2. 写一个求平方根的方法,第一个参数x为一个整型的操作数,第二个参数y也为整型,表示允许误差
function mySqrt (x, y) {
let result;
...
return result;
}
满足
x - result * result <= y
请将函数补充完整(不要用Math.sqrt())
function mySqrt (x, y) {
let result;
let start = 0, end = x, mid;
while(true) {
mid = (start + end) / 2;
if (Math.abs(x - mid * mid) <= y) {
result = mid;
break;
}
if (x > mid * mid) {
start = mid;
}
if (x < mid * mid) {
end = mid;
}
}
return result;
}
mySqrt( 100, 0.01 );