I want to find (using JS) the greatest 3-digit number that
This is my code:
var bool = false;
for(var i = 999; bool == true; i = (i - 1)) {
if(i % 2 == 1 && i % 3 == 2 && i % 4 == 3 && i % 5 == 4) {
bool = true;
alert(i);
}
}
But it did not work (somehow there was no error messages, and the alert did not show up). So how can I find that 3-digit number? Thanks.
The loop continuation condition for your loop is bool == true
, which is false when the loop starts and so the loop will never execute. Use this instead:
for(var i = 999; i > 0 && !bool; i = (i - 1)) {
or this to strictly obey the "three-digit number" requirement:
for(var i = 999; i >= 100 && !bool; i = (i - 1)) {
I'd also suggest finding a better variable name than bool
. found
would be appropriate here.
Your breaking condition is wrong here change it to:
var bool = false;
for(var i = 999; !bool; i--) {
if(i % 2 == 1 && i % 3 == 2 && i % 4 == 3 && i % 5 == 4) {
bool = true;
alert(i);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.