繁体   English   中英

井中蜗牛 javascript 挑战

[英]snail in the well javascript challenge

这是我关于堆栈溢出的第一个问题,尽管在我没有获得足够的详细信息来理解为什么以这种方式编写代码之前已经回答了这个问题,而且我不只是想在不理解的情况下复制和粘贴解决方案。

蜗牛每天爬 7 英尺,每晚滑回 2 英尺,蜗牛需要多少天才能从给定深度的井中钻出来? 示例输入31示例 Output 6 这是我写的,但没有用

function main() {
var depth = parseInt(readLine(), 10);
//your code goes here
let climb = 0, days = 0;
   for(climb + 7; climb < depth; days++){
       climb += 2;
       console.log(days);
   


只需输入并写下这个var day= Math.ceil((depth-2)/5); 和 output 那个!

/* day --> 7++
night --> 2-- */
var day = 0;
var total = 0;
var input = 41;
 while (input>total){
     day++;
     total+=7;
   if (total>=input){
       console.log(day);
       break;
   }
   total = total -2
 }

如评论中所述,无需循环。 只需计算问题的数学并使用它。

 function snailCalc (depth, dailyGain, nightlyLoss) { var days = 1; var netGain = dailyGain-nightlyLoss; if(depth > dailyGain ) { //Basic calc based on net gain taking the first day into account days = (depth-dailyGain)/netGain; //Add the fist day days += 1; //We want whole days so use Mathc.ceil days = Math.ceil(days) //Or we could do all that in one line //days = Math.ceil(((depth-dailyGain)/netGain) + 1); } return days; } const gain = 7; const loss = 2 for(var d = 1; d < 31; d++) { console.log(`Depth: ${d}, Days: ${snailCalc(d, gain, loss)}` ) }
 Bob

function main() {
    var depth = parseInt(readLine(), 10);
    console.log(Math.round(depth / 5))
}

尝试这个:

  var depth = parseInt(readline(), 10);
  var day = 0;
  for(let climb = 0; climb <= depth;) {
      day +=1;
      climb += 7;
      if(climb >= depth) {
          break;
      }
      climb -= 2;
  }
  console.log(day);
 function main() {
 var depth = parseInt(readLine(), 10);
//your code goes here
var days=1;
var level =0;
for(level =0;level<depth;days++){
    level+=7
    if(level<depth){
        level-=2;
    } else{
        break ;
    }
    
}console.log(days)

}

试试这个,几天前我遇到了同样的麻烦,我们发现错误是使用js你需要重置变量,如果蜗牛那天爬的距离大于结束的深度,你需要在再次评估之前对结果求和循环。

depth = 31;
let days = 0;
let climb = 0;

while(climb < depth){
    let result = climb + 7;
    if(result  >= depth){ 
        days++;
        break;
    }
    climb = result - 2;
    days++;
    //console.log("climb ",climb);

}

console.log(days);

您可以更改 function 输入并测试代码片段:

更多你可以运行代码并检查结果↗

例如:main(128) // 26

 function main(input) { let depth = input let climbsUp = 7 let slipsBack = 2 let distance = climbsUp - slipsBack let days = 0; let rDepth = Math.round(depth / distance) for (let i = 0; i < rDepth; i++) { distance = distance + 5 days = ++days if (days === 6) { console.log('days will it take the snail to get out of a well: ' + rDepth) } else { console.log('days will it take the snail to get out of a well: ' + rDepth) break; } } } main(42); main(128);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM