【问题标题】:average function not working properly, what is wrong with it?平均功能无法正常工作,有什么问题?
【发布时间】:2021-01-30 10:39:35
【问题描述】:

我是学习 Javascript 的新手,为什么我的函数没有查看正确答案?你能帮我理解它有什么问题吗? 因为如果计算是


<html lang="en">
 <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Document</title>
     <script>
         function type() {
            let maths = prompt('Please type grade in Math');
            let physics = prompt('Please type grade in Physics');
            let chemistry = prompt('Please type grade Chemistry');
                
            let grade = (maths + physics + chemistry)/3;
                    
               if (grade < 70) {
                  document.write('Your grade is: ' + 'C')
               } else if (grade > 70 && grade < 90) {
                  document.write('Your grade is: ' + 'B')
               } else {
                  document.write('Your grade is: ' + 'A');
               }
        }
        type();


     </script>
 </head>
 <body>
     
 </body>
 </html>


【问题讨论】:

  • 没有尝试过代码并且你没有告诉我们它有什么问题(通过示例),但至少将第二个条件从等级 > 70 更改为等级 >= 70。

标签: javascript html function average


【解决方案1】:

问题在于prompt 返回的是字符串,而不是数字。下面的示例使用parseFloat 将其转换为数字,以便您计算平均值。

最好使用number inputs,它允许您设置最小和最大允许值并为您处理一些验证。

另外,如果我为每个班级输入 0,我仍然会得到 C,我不确定是否有意义。

<html lang="en">
 <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Document</title>
     <script>
         function type() {
            let maths = parseFloat(prompt('Please type grade in Math'));
            let physics = parseFloat(prompt('Please type grade in Physics'));
            let chemistry = parseFloat(prompt('Please type grade Chemistry'));
                
            let grade = (maths + physics + chemistry)/3;
                    
               if (grade < 70) {
                  document.write('Your grade is: ' + 'C')
               } else if (grade > 70 && grade < 90) {
                  document.write('Your grade is: ' + 'B')
               } else {
                  document.write('Your grade is: ' + 'A');
               }
        }
        type();


     </script>
 </head>
 <body>
     
 </body>
 </html>

【讨论】:

  • @Mark 不客气!继续学习,祝你好运:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-06
  • 2017-07-08
  • 1970-01-01
  • 2022-07-29
  • 2017-09-23
  • 1970-01-01
相关资源
最近更新 更多