这个例子用权重来达到随机的效果。
<script type="text/javascript">var totalWeightedScore
var lastScore
var totalCredit
var gainCredit
function checkScore(fs){
if(isNaN(fs) || fs <0 || fs >100){
alert("分数输入错误,范围0-100,请重新输入")
return false
}
return true
}
function checkCredit(is){
if(isNaN(is) || is <1 || is >4){
alert("分数输入错误,范围1-4,请重新输入")
return false
}
return true
}
function getNextScore(){
var data = window.prompt("请输入下一门课程的成绩,输入-1表示结束", '0')
var fs = parseFloat(data)
if(fs == -1){
endX()
return
}
if(!checkScore(data)){
getNextScore()
}else{
lastScore = fs
getNextCredit()
}
}
function getNextCredit(){
var data = window.prompt("请输入课程的学分", '0')
var is = parseInt(data)
if(!checkCredit(is)){
getNextCredit()
}else{
totalCredit += is
if(lastScore >= 60){
gainCredit += is
}
totalWeightedScore += lastScore * is
getNextScore()
}
}
function startX(){
lastScore = -1
totalWeightedScore = 0
totalCredit = 0
gainCredit = 0
getNextScore()
}
function endX(){
if(lastScore == -1){
alert("未输入任何分数与学分")
return
}
var weightedScore = totalWeightedScore / totalCredit
weightedScore = Math.round(weightedScore * 100) / 100
var info = "加权平均分:" + weightedScore
+ "\n总学分数:" + totalCredit
+ "\n及格总学分数:" + gainCredit
if(gainCredit == totalCredit){
info += "\nAll Pass"
}else if(gainCredit <totalCredit / 2){
info += "\n二一不及格"
}
alert(info)
}
</script>
<input type="button" value=" 开始 " onclick="startX()"/>