提问者:小点点

返回值始终未定义


我正在尝试使用递归实现GCD函数,但是当我制作一个返回值时,它总是返回未定义的,而如果我制作了一个console.log(值),它会正确地显示它?

下面是我使用的代码:

null

let a = 6
let b = 4

var gcd = gcdRec(a, b)
console.log(gcd) //this executes undefined



function gcdRec(a, b) {
  var gcd = 0
  if (a % b === 0) {
    gcd = b
    return gcd //if i used console.log(gcd) it prints correctly

  } else {
    var temp = b
    b = a % b
    a = temp
    if (b === 0) {
      gcd = a
      return gcd
    }
    gcdRec(a, b)
  }
}

null

在使用gce之前,我也试图定义它,如让gcd=0然后gcd=gcdRec(a,b),但它仍然是一样的。 知道它为什么这么做吗?


共1个答案

匿名用户

在函数中为每个条件给出返回语句

null

let a = 6
let b = 4

var gcd = gcdRec(a, b)
console.log(gcd) //this executes undefined



function gcdRec(a, b) {
  var gcd = 0
  if (a % b === 0) {
    gcd = b
    return gcd //if i used console.log(gcd) it prints correctly

  } else {
    var temp = b
    b = a % b
    a = temp
    if (b === 0) {
      gcd = a
      return gcd
    }
   return gcdRec(a, b)
  }
}