2012-09-09 74 views
0

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

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

以下是我已经做了:提前任何帮助

<!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> 

感谢。

+1

这是功课? – j08691

+0

两年后,价格不会是原来的96%。这将是原来的96.04%。 – Isaac

+1

无论你卖什么,请注册50年 –

回答

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: $' + ...); 
+0

对你发布这个很有帮助。顺便说一句,为什么不只是使用'折扣* = 0.98;'? :) – Nick

+0

@Nick:我只是明确地显示'0.98'的来源。 – Blender