一些提示()评论练习

时间:2014-03-05 03:59:32

标签: javascript

我在javascript上非常初级,我想找到这些练习的解决方案: 1.编写一个脚本,提示访问者输入两个数字[使用JavaScript内置函数prompt()]。然后,显示两个数字及其总和如下:

You entered: 5 and 2
Sum:  7
  1. 编写一个脚本,提示访问者输入两个数字,然后在文档中显示两个数字及其总和,差异,乘积,商和模数。例如,如果访问者输入52,结果将显示如下:
  2. You entered:  5 and 2
    Sum: 7
    Difference: 3
    Product: 10
    Quotient: 2.5
    Modulus: 1
    
    1. 编写一个脚本,提示访问者输入三个数字,然后计算并显示他们的平均值。

    2. 编写一个脚本,提示访问者他/她当周工作的小时数。不要忘记超过40的时间是在一半时间内支付的。以下是访问者在35 hours输入$10/hour时的显示效果:

    3. Total Hours Worked:   35
      Regular Pay:  35  hours @ $10/hour =  $350
      Overtime Pay:  0 hours  @ $15/hour = $0
      Total Pay:  $350
      

2 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

(function(show, askFor){
  var first = +askFor("The first number:"),
    +second = askFor("The second number:");
  show([
    "You entered:", first, "and", second, 
    "Sum:", first+second
  ].join(" "));
})(alert, prompt);

(function(show, askFor){
  var first = +askFor("The first number:"),
    second = +askFor("The second number:");
  show([
    "You entered:", first, "and", second,
    "Sum:", first + second,
    "Difference:", first - second,
    "Product:", first * second,
    "Quotient:", first / second,
    "Modulus:", first % second
  ].join(" "));
})(alert, prompt);

(function(show, askFor){
  var first = +askFor("The first number:"),
    second = +askFor("The second number:"),
    third = +askFor("The third number:");
  show("The average of those numbers: "+ (first+second+third)/3);
})(alert, prompt);

(function(show, askFor){
  var hours = +askFor("How much you worked this week:"),
    rate = +askFor("And what's your hourly rate:"),
    overtimeRate = rate*1.5,
    regularHours = Math.min(40, hours),
    overtimeHours = Math.max(0, hours-40),
    regularPay = rate*regularHours,
    overtimePay = overtimeRate*overtimeHours;
  show([
    "Total Hours Worked:", hours,
    " Regular Pay:", regularHours, 
    " hours @ $", rate, "/hour", 
    " = $", regularPay, 
    " Overtime Pay:", overtimeHours,
    " hours @ $", overtimeRate, "/hour",
    " = $", overtimePay, 
    " Total Pay: $", regularPay+overtimePay  
  ].join(""));
})(alert, prompt);

答案 1 :(得分:0)

您可以使用javascript prompt方法将用户输入的值保存在变量中:

var num1 = prompt("Enter first number");

您可以使用相同的代码从用户那里获取num2,num3,而不是进行计算并获得结果。

注意:练习是学习javascript的最佳选择,或者我必须说些什么。所以继续练习,每当你遇到任何问题时,请告诉我们。我们都在这里互相帮助。