0

我需要编写一段代码来请求合同年数的值。然后用for循环计算每年2%的折扣系数,即如果是一年合同,价格是全价的98%,如果是两年合同,价格是96%的全价,等等。

我似乎有点卡住了,不确定我是否完全理解了他们的要求。

这是我已经做的:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transition//EN" "http://www.w3.org/TR/xhtml/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<body>
    <script type = "text/javascript">

    var stringVariable = prompt ("Enter the number of people")
    var numberVariable
    var loopCounter = prompt ("How many years?");
    var numberCount = new Array(100/2);

    if (stringVariable <= 30) {
        numberVariable = 15*stringVariable;
    }
    else if (stringVariable> 30 && stringVariable<60) {
        numberVariable = 12*stringVariable;
    }
    else if (stringVariable>60) {
        numberVariable =12*stringVariable;
    }

    alert ("Total cost is: $" + numberVariable);

    for (loopCounter = 0; loopCounter <= 4; loopCounter++)
    {
        document.write("Total discount $" + loopCounter - numberCount[loopCounter] + "<br />");
    }

    alert ("Total cost is: $" + numberVariable - numberCount);

    </script>

</body>
</html>

提前感谢您的帮助。

4

1 回答 1

3

您的代码似乎在某些地方存在根本缺陷,尤其是您的变量名。

这是我解决问题的方法:

// parseInt() converts strings into numbers. 10 is the radix.
var num_people = parseInt(prompt('Enter the number of people'), 10);
var num_years = parseInt(prompt('How many years?'), 10);

// Initialize your variables.
var cost = 0;
var discount = 1.00;

// Your if condition was a bit odd. The second part of it would be
// executed no matter what, so instead of using else if, use an
// else block
if (num_people <= 30) {
  cost = 15 * num_people;
} else {
  cost = 12 * num_people;
}

alert('Total cost is: $' + cost);

// Here is a for loop. i, j, k, ... are usually
// used as the counter variables
for (var i = 0; i < num_years; i++) {
  // Multiplying by 0.98 takes 2% off of the total each time.
  discount *= 1.00 - 0.02;

  // You fill the rest of this stuff in
  document.write('Total discount $' + ... + '<br />');
}

// And this stuff
alert('Total cost is: $' + ...);
于 2012-09-09T03:55:10.717 回答