javascript的蜗牛挑战



这是我关于堆栈溢出的第一个问题,尽管这个问题以前已经回答过了,但我没有得到足够的细节来理解为什么代码是这样写的,我不想在不理解的情况下复制和粘贴解决方案。

蜗牛每天爬7英尺,每晚滑回2英尺。在给定的深度下,蜗牛需要多少天才能出井?样本输入31样本输出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 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);

只需输入并编写var day= Math.ceil((depth-2)/5);并输出!

/* 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))
}
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);

您可以更改函数输入并测试狙击手:

有关更多信息,您可以运行代码并检查结果↗

例如: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);

最新更新