Javascript 测试一个数是否等于两个连续斐波那契数的乘积
这里是一个链接 基本上,任务是测试一个随机传递的数字是否等于两个连续斐波那契的乘积Javascript 测试一个数是否等于两个连续斐波那契数的乘积,javascript,Javascript,这里是一个链接 基本上,任务是测试一个随机传递的数字是否等于两个连续斐波那契的乘积 function productFib(prod) { var x = [] var z; var a = 0 var b = 1 var c = 7 var h = 1000 while (c < 100) { var t = a + b var a = b var b = t x.p
function productFib(prod) {
var x = []
var z;
var a = 0
var b = 1
var c = 7
var h = 1000
while (c < 100) {
var t = a + b
var a = b
var b = t
x.push(t)
c++
}
for (var i = 0; i < h; i++) {
if (prod = x[i] * x[i + 1]) {
z = [x[i], x[i + 1], true]
} else {
z = [x[i], x[i + 1], false]
}
}
return z
}
函数productFib(prod){
变量x=[]
var z;
变量a=0
var b=1
变量c=7
var h=1000
而(c<100){
var t=a+b
变量a=b
var b=t
x、 推力(t)
C++
}
对于(变量i=0;i
首先,我创建一个生成斐波那契数的函数,然后将它们传递给一个数组。这是经过测试的,所以我想问题不在那里。然后我尝试创建一个for循环,它将每2个数字相乘,然后检查它们是否等于随机数
至少这是我的想法,但每次我都会得到类似-[1,2,true]
或[undefined]
的结果。此代码有效:
function productFib(prod){
var x = []
var z;
var a = 0
var b = 1
var c = 0
var h = 1000
var t=0
//Edited the loop to only check numbers below the one you are looking
// to make(prod) because any two consecutive numbers over that will not produce the
// number you are looking for(14*any number above that cannot make 13)
while( t < prod){
//removed c++
t = a + b
var a = b
var b = t
x.push(t)
}
//Set the loop to loop through the whole array(x.length)
for(var i = 0; i < x.length; i++){
if(prod == x[i]*x[i+1]){ //Added a double equals sign
z =[x[i], x[i+1], true]
//For testing
console.log(x[i] + ' and '+x[i+1] + ' make ' + prod)
//Return the number when one is found, not after looking through
//the whole array
return z
}
}
//In case none are found
return false
}
productFib(4895) //this is the multiplication of 89 and 55, successive fib's
函数productFib(prod){
变量x=[]
var z;
变量a=0
var b=1
var c=0
var h=1000
var t=0
//编辑循环以仅检查您正在查看的循环下方的数字
//做(戳),因为上面的任何两个连续数字都不会产生
//您正在寻找的号码(14*以上任何号码不能成为13)
while(t
这里有一个演示:
注释中详细说明了这些更改
prod=x[i]*x[i+1]
可能应该使用=
而不是=
。在第二个循环中的每次迭代中,您都会覆盖z
。它可能曾经有一个值为true
,但您仍然返回一个值为false
。您应该尝试找到一个根本不需要数组的解决方案。您可能不希望var
关键字在while
循环中。与问题无关,但是请为变量使用相关的名称。为什么要先执行t=true
,然后执行t=a+b
?你打算做什么?为什么你仍然在做c++
,即使它没有在任何地方使用?我试图尽可能多地维护OP的代码,以便他能看到发生了什么。首先!非常感谢你。在本练习中-如果为false,我必须返回具有相同数字的相同数组,但使用“false”而不是“true”。应为“[89,144,false]”,而不是“false”-知道如何操作吗?