简体   繁体   English

javascript-查找整数的余数不起作用

[英]javascript - Finding remainder of integer not working

I want to find (using JS) the greatest 3-digit number that 我想找到(使用JS)最大的3位数字

  • leaves a remainder of 1 when divided by 2 除以2时余数为1
  • leaves a remainder of 2 when divided by 3 除以3时剩下2的余数
  • leaves a remainder of 3 when divided by 4 除以4时剩下3的余数
  • leaves a remainder of 4 when divided by 5 除以5时剩下4的余数
  • 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. 循环的循环延续条件为bool == true ,当循环开始时为false,因此循环将永远不会执行。 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 . 我还建议找到一个比bool更好的变量名。 found would be appropriate here. found这里found合适的。

    Your breaking condition is wrong here change it to: 您的破损条件错误,将其更改为:

    Here is Demo 这是演示

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

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

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