所以我在我的介绍编程课中有一个非常具体的作业。我想用一个while循环和一个提示框来计算五个“游戏分数”的平均值。然后我必须将我的代码插入一个函数,然后使用一个按钮调用该函数。我一直在努力让它发挥作用,我很确定这可能是一个简单的错误让我退缩,这让人更加沮丧。
function Q1() {
var sum = 0;
var avg = 0;
var sc1 = 0;
var x = 1;
alert("problem #2 find the average of five game scores");
while (x < 5) {
sc1 = prompt("enter the score from game # " + x);
sum = parseFloat(sc1) + parseFloat(sum);
avg = sum / x;
x = x++;
document.write(avg);
}
};
<input type="button" value="run problem #2" onClick="Q1()" ;/>
答案 0 :(得分:1)
您的代码中几乎没有错误。
function Q1() {
var scores = 0;
var x = 1;
alert("problem #2 find the average of five game scores");
while (x <= 5) {
scores += parseFloat(prompt("enter the score from game # " + x));
x++;
}
document.write(scores/5);
}
function Q1() {
var average = 0;
alert("problem #2 find the average of five game scores");
for (var x=0; x < 5; x++)
average += parseFloat(prompt("enter the score from game # " + x))/5;
document.write(average);
}
function Q1(games) {
var average = 0;
alert("problem #2 find the average of five game scores");
for (var x=0; x < games; x++)
average += parseFloat(prompt("enter the score from game # " + x))/games;
document.write(average);
}
答案 1 :(得分:0)
尝试这个找到5的平均值没有,你做了愚蠢的错误:
<html>
<body>
<input type="button" value="run problem #2" onClick="Q1()";/></br>
<script type= "text/javascript">
function Q1(){
var sum= 0;
var avg= 0;
var sc1= 0;
var x = 0;
alert ("problem #2 find the average of five game scores");
while(x < 5){
sc1=prompt("enter the score from game # " + (x+1));
sum = parseFloat(sc1)+sum;
x++;
}
avg = sum/5;
document.write(avg);
};
</script>
</body>
</html>
答案 2 :(得分:0)
变量在原件上使用的方式有点令人困惑,所以这就是我的建议。
HTML 的
<input type="button" value="run problem #2" onClick="Q1()"/>
<br/>
JS
function Q1(){
var sum= 0;
var avg= 0;
var score= 0;
var x = 1;
var g = 5;
alert ("problem #2 find the average of five game scores");
while(x <= g){
score=prompt("enter the score from game # "+x);
sum += parseFloat(score);
x++;
}
avg = sum /g;
document.write("Average is " + avg);
}
答案 3 :(得分:0)
试试这个。
<script>
function Q1() {
var sum = 0;
var avg = 0;
var sc1 = 0;
var x = 0;
alert("problem #2 find the average of five game scores");
while (x < 5) {
sc1 = prompt("enter the score from game # " + (x+1));
sum = parseFloat(sc1) + parseFloat(sum);
x++;
}
avg = sum / x;
document.write(avg);
};
</script>