【问题标题】:Adding looped prompts together to get a sum将循环提示加在一起以获得总和
【发布时间】:2018-03-08 10:38:16
【问题描述】:

出于某种原因,循环只是让我陷入循环。 我在创建和确定要增加的正确变量和不增加的变量时遇到问题。

无论如何,我必须使用循环不断提示用户输入一个数字,直到他们输入 0,然后将所有输入加在一起。

所以我的基本代码是:

let numPrompt = +prompt("Enter a number");
if (isNaN(numPrompt)) {
  numPrompt = +prompt("Enter a number");
}
while (numPrompt != 0) {
  numPrompt = +prompt("Enter another number");

  console.log(numPrompt);
}

哪些循环可以一直要求输入直到 0。但是我在考虑如何跟踪输入然后将它们全部加起来为 1 值时遇到了问题。

【问题讨论】:

    标签: javascript while-loop


    【解决方案1】:
    let inputArray = new Array();
    let sum = 0;
    let numPrompt;
    
    do{
        numPrompt = prompt( "Enter a number" );
      var value = parseInt( numPrompt );
    
      if( Number.isInteger( value ) ){
        inputArray.push( value );
        sum += value;
        console.log( "Number: " + value );
      }
    }
    while( numPrompt != '0' );
    
    console.log( sum );
    

    如果用户输入的是字符而不是整数,则需要进行处理。

    inputArray 用于跟踪所有用户输入(如果不需要保存,可以跳过)

    http://jsfiddle.net/3Jtxu/25/

    【讨论】:

      【解决方案2】:

      您可以编写如下版本:

      n=0;
      while (n<10) {
           n+=parseInt(prompt('enter a number'));
      }
      

      一直持续到n&gt;=10

      如果你想在输入0时终止,你需要一个额外的变量来存储输入的值:

      n=0;
      pr=-1;
      while (pr!=0) {
           pr=parseInt(prompt('enter a number'));
           n+=pr;
      }
      

      【讨论】:

        【解决方案3】:

        很好的尝试!不过,有几件事我想指出。当您调用 prompt() 时,用户输入的任何内容都将是字符串类型。因此,当您使用 isNaN() 进行验证时,它将始终返回 true。

        接下来,由于 prompt() 返回字符串,您需要使用 parseInt() 将其转换为整数,如下面的代码所示。

        最后,在您的循环中,每次迭代都会为 numPrompt 重新分配一个新值。您需要将等号更改为“+=”以增加 numPrompt,或声明另一个变量(总计)以保存所有用户输入的总数,再次使用“+=”运算符,即显示的内容下面。

        然后我们在循环完成后记录总数。

        let total = 0;
        let numPrompt;
        
        while (numPrompt != '0'){
          numPrompt = prompt("Enter another number")
          total += parseInt(numPrompt)
        
          // Log each input
          console.log(numPrompt)
        } 
        
        // Log the total
        console.log(total)
        

        【讨论】:

        • 谢谢,这肯定是我忘记的,+=,以及我认为我在整数上没问题,因为我有它作为 +prompt?我对那个命令是正确的还是用户 Number 或 parseInt 会更好?
        • 我不太确定,我从来没有看到加号被用得太多,所以我不得不做一些挖掘工作。 stackoverflow.com/questions/17106681/… 对此有一些很好的信息。
        • 使用+expressionexpression 转换为整数。这是一种晦涩难懂的方法,我宁愿避免使用parseInt(expression)
        【解决方案4】:
        var input = prompt("Enter a number");
        var min = parseInt(input);
        
        while (input !== "0") {
        input = parseInt(input);
        if (input < min) {
            min = input;
        }
        input = prompt("Enter a number");
        }
        alert(min);
        

        http://jsfiddle.net/3Jtxu/6/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-08-17
          • 2013-05-08
          • 2013-01-05
          • 1970-01-01
          • 2014-11-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多