+ 1
Hello, I want to know what is wrong in my program
This program calculate how day take a snail to be out, in day he run 7 feet and at night -2 function main() { var di = parseInt(readLine(), 10); var s=0 var f; var d=0; do{ d=d+1 f=s+7; if (f==di){ console.log(d) break; } s=f-2; }while (s!=di); if (s==di){console.log(d)} }
7 Answers
+ 3
f value can exceed the di . Then there is no stoping loop.
Use >= instead of == , in if condition.
And no need to print d again out side loop.
+ 3
function main() {
var di = parseInt(readLine(), 10);
var s=0
var f;
var d=0;
do{
d=d+1
f=s+7;
if (f >=di ){
console.log(d)
break;
}
s=f-2;
}while (s!=di);
//if (s==di){console.log(d)}
}
See if you use
if( f==di)
break ;
Then what if example di = 30 but f = 34 , you should break the loop as it reaches depth already. But f==di is not true so it won't stop loop and s!=di (32!=30) is true so it continues loop so never after f==di comes true. Then it is infinite loop.
You must use condition
if( f >= di)
break;
And if you print day value before break then no need to print after loop. Of course if condition is false though. So Never print I think.
+ 2
Thank you, in the first time I guessing that you talk about the second if sorry
But I don't understand why my first solution is wrong can you explain please because I really need the answer.
+ 1
It said in output "execution timed out
"
+ 1
Yes. It is because infinite looping..
Read my reply âagain for solution.
+ 1
Thank you very much for help,
+ 1
Side note: get used to using meaningful variable names. They help a lot in debugging.