我是一个初学者,这是我的第一篇文章(加上我不是以英语为母语的人),所以如果我的代码和/或我的英语不好,请原谅我。给定两个数字,我想编写一个 JavaScript 函数查找第二个是否是第一个的幂,然后确定该幂(例如:2,8,输出必须是 3)。我写了两个函数,都可以工作,但我无法将它们放在一起。
这是第一个检查第二个数字是否是第一个数字的幂的函数。
function checkNumbers(x,y){
if (y%x !==0){
return "this numbers are not valid"
}
else if(x===y) {
return "correct!"
}
else {
y=y/x
return checkNumbers(x,y)
}
}
checkNumbers(2,8) // will give the first answer
checkNumbers(2,18) // will give the second answer
第二个函数将为您提供积分对数:
count =1;
function findGrade(x,y) {
if(y/x===1)
return "the grade is " + count;
count++;
y = y/x;
return findGrade(x,y)
}
findGrade(2,8) // output 3
findGrade(2,16) // output 4
如何将它们组合成一个函数?我想我需要一个关闭,但我没有找到实现该功能的方法。
最佳答案
checkNumbers
应返回 bool 值,而不是消息。然后 findGrade 可以检查该结果以查看是否应该计算对数。像这样的事情:
function checkNumbers(x,y){
if (y%x !==0){
return false
}
else if(x===y) {
return true
}
// the rest of your function remains the same.
function findGrade(x,y) {
// First, check to see whether y is a power of x
if checkNumbers(x,y) {
// your original findGrade function goes here
}
else
return -1; // Use this as a failure code.
这对你有用吗?
另一种可能性是将这些函数完全组合起来:尝试找到对数(您所说的“等级”);如果有效,你就会得到答案;如果失败(在y%x !== 0
),那么您将报告失败。
关于javascript - 我如何将两个函数放在一起,两个函数内部都有递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44854754/