Javascript提示和警报输入一个数字,它将循环,你将输入数字,以获得它的平均值 [英] Javascript prompt and alert inputting a number and it will loop and you will input numbers to get the average of it

查看:59
本文介绍了Javascript提示和警报输入一个数字,它将循环,你将输入数字,以获得它的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在循环下面有javascript代码,但我无法得到它的平均值。我不确定我的代码有什么问题。这就像你输入一个数字的第一个提示,它会循环,你输入的数字就像你输入的数量一样,你将获得所有数字的总和,并在完成后得到它的平均值。这是我的代码。

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 will loop and you input numbers like how much you entered and you will get the sum of all the numbers and get the average of it after it's done. Here's the code that I have.

function show_prompt()
{

function show_prompt() {

    var n=prompt("Input a number: ", "Number here");
    if (n==n)
    {
      var i=1;
      do
      {
        var g=prompt("Input grade: " );

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

      }
      while(i<=n);
    }
    var average=(total)/n;
    document.write("Average is: " +average);
}

提前致谢!

推荐答案

您在每个区间中覆盖总变量,其等级值加倍。

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

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

应更改为

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

此外,您需要在代码的开头初始化total变量。
请参阅演示代码: http://jsfiddle.net/56ouvan3/1/

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

我还建议进行一些输入验证(例如检查平均要求的成绩数是否大于0,所有成绩都是正数等)

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.)

这篇关于Javascript提示和警报输入一个数字,它将循环,你将输入数字,以获得它的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆