我试图理解为什么我输入的scores1,score2和scores3
被当作一个字符串。例如:得分1 = 1,得分2 = 1,得分3 =1。平均得分
计算为111/3,而不是3/3。
player1 = prompt(" Welcome Player 1! Please Enter your name ");
alert(" Hello, " + player1+".");
p1score1 = prompt(' Enter first score. ');
p1score2 = prompt(' Enter second score. ');
p1score3 = prompt(' Enter third score. ');
/*p1score1 = 89;
p1score2 = 120;
p1score3 = 103;
*/
p1avgScore = (p1score1 + p1score2 + p1score3)/3;
console.log(" Congratulations " + player1 + ". Your scores are: " +
p1score1 + ", " + p1score2 + ", " + p1score3 + ".");
console.log(" Your average score of all three games are: " +
p1avgScore);
答案 0 :(得分:2)
这是因为prompt()
函数returns a string而不是导致(p1score1 + p1score2 + p1score3)
产生字符串p1score1
,p1score2
和{{ 1}},而不是对所有要素进行关节置换(即加法)。
请考虑进行以下调整并添加p1score3
来解决此问题:
parseFloat()
这样做,将每个p1score1 = parseFloat( prompt(' Enter first score. ') );
p1score2 = parseFloat( prompt(' Enter second score. ') );
p1score3 = parseFloat( prompt(' Enter third score. ') );
的结果解析为一个数字,这意味着prompt()
等的值类型为p1score1
。现在,这意味着将在此行执行加法操作,而不是字符串连接:
number
希望有帮助!
(p1score1 + p1score2 + p1score3)/3
答案 1 :(得分:1)
您只需要将输入解析为整数/浮点数即可。
player1 = prompt(" Welcome Player 1! Please Enter your name ");
alert(" Hello, " + player1+".");
p1score1 = parseInt(prompt(' Enter first score. '));
p1score2 = parseInt(prompt(' Enter second score. '));
p1score3 = parseInt(prompt(' Enter third score. '));
/*p1score1 = 89;
p1score2 = 120;
p1score3 = 103;
*/
p1avgScore = (p1score1 + p1score2 + p1score3)/3;
console.log(" Congratulations " + player1 + ". Your scores are: " +
p1score1 + ", " + p1score2 + ", " + p1score3 + ".");
console.log(" Your average score of all three games are: " +
p1avgScore);