【问题标题】:Write a program that asks a user to enters pairs of numbers until they enter "quit". add the numbers using a function [duplicate]编写一个程序,要求用户输入成对的数字,直到他们输入“退出”。使用函数添加数字[重复]
【发布时间】:2021-05-14 14:40:40
【问题描述】:

“编写一个程序,要求用户输入一对数字,直到他们输入“退出”。当输入并验证每对数字时,使用函数添加数字。该函数将有两个参数用于数字并返回总和。用户输入“退出”后,输出所有数字对及其总和。”

这是我下面的函数

function evaluatingUserInput() {
    
    // Variable declaration.
    var numberOne;
    var numberTwo;
    var total = 0;
    
    // While user input is not the string "quit" prompt the user again.
    while(numberOne != "quit"){

        numberOne = prompt("Please enter a number or quit to stop.");
        numberTwo = prompt("please enter a second number or quit to stop.");

        numberOne = Number(numberOne);
        numberTwo = Number(numberTwo);
        total = numberOne + numberTwo;
            
        document.write(numberOne + " + ");
        document.write(numberTwo + " = ");
        document.write(total);
        document.write("<br />");
    }
}

【问题讨论】:

    标签: javascript for-loop while-loop


    【解决方案1】:

    我不太确定您想要达到什么目标,但我会尽力帮助您。我不想给你任何虚假信息。

    首先,我不会使用while(),而是使用setInterval()

    setInterval(function(){ 
     if (numberOne != "quit") {
      //the code you had inside while()
     }
    }, 1);
    

    另外,document.write 将覆盖您在文档中的所有内容。所以我不会这样做,而是使用这个:

    var number = document.createElement("P")
    number.innerHTML = numberOne + " + " + numberTwo + " = " + total;
    document.body.appendChild(number)
    

    【讨论】:

    • setInterval() 绝对不能替代while(),不是以您描述的方式,也不是以任何其他方式。
    • 所以该函数的目标是不断提示用户输入两个数字,直到他们输入字符串“quit”。它希望您获取第一个输入,将其添加到第二个输入并输出答案。重复此操作,直到用户输入字符串退出。 document.write 存在于打印到 html 文档的函数内部。
    • @PeterB 我会将其用作预定循环。我就是这样做的,我不知道你为什么有这样的问题。如果您尝试以不同的方式进行操作,那么这没有问题。但我使用setInterval() 作为循环,它对我有用,每毫秒。
    • 两者的意思完全不同。 setInterval(fn, t) 在实践中意味着:只要系统空闲就运行fn,并且自上次调用以来至少经过了t 毫秒。将其与 while(condition) { ... } 进行比较,这意味着:只要 condition 等于 true,就运行正文语句,并在正文结束后再次重复此操作。只是完全不一样。效果可能看起来很相似,因为 javascript 是单线程的,但是 两者背后的功能完全不同,并且两者的用途完全不同
    • @PeterB 我曾经尝试使用while() 一次。由于某种原因,它不起作用。但是我试图实现的目标与setInterval() 一起工作,所以根据我所做的,setInterval() 有时可以,但我并不总是这么说。因此,基于我当时尝试做的事情,它奏效了。我仍然可以使用 if()setInterval() 的条件。
    猜你喜欢
    • 2015-06-25
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多