Javascript prompt and alert inputting a number and it will loop and you will input numbers to get the average of it

前端 未结 3 773
悲&欢浪女
悲&欢浪女 2021-01-24 17:07

I have below javascript code with loop but I can\'t get the average of it. I\'m not sure what\'s wrong with my code. It\'s like the first prompt you will input a number and it w

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-24 17:47

    You are overriding your "total" variable in each interval with double the grade value.

    var grade=parseInt(g);
     var total=grade+grade;
    

    should be changed to

    var grade=parseInt(g);
     total=total+grade;
    

    Also, you need to initialize the "total" variable in the beginning of your code. See demo code: http://jsfiddle.net/56ouvan3/1/

    I would also recommend some input validation (such as checking that the number of grades requested to average are greater than 0, all grades are positive, etc.)

提交回复
热议问题