Calculating the mean value of the numbers provided in the input

I'm struggling with calculating the average of numbers entered through a prompt window. I want to display the numbers as I've done so far, but combining them to find the average is proving difficult.

Here's the code I have:

<html>
<body>

<script type="text/javascript">
function show_prompt() {
    i = 0;
    do {
        var number = prompt("Please Enter a Number");
        var number = parseInt(number);
        i++;

        document.write("Number: " + number);
        document.write("<br>");
        
    }
    while (i < 5);
}
show_prompt();
var avrg = number + number + number + number + number
document.write('Average of scores : ' + avrg);     
</script>   
</body>
</html>

Answer №1

Make sure to move the calculation inside the function for a more efficient approach. Here's a simpler way of achieving the same result:

function show_prompt() {
  var i = 0;
  var sum = 0; // variable to store the sum of numbers
  do {
    var number = prompt("Please Enter a Number");
    sum += parseInt(number); // add the entered number to sum
    i++;

    document.write("Number: " + number);
    document.write("<br>");

  }
  while (i < 5);

  document.write('Average of scores : ' + sum / i);
}
show_prompt();

Here are some comments on your previous code with mistakes:

function show_prompt() {
    i = 0;
    do {
        // no need to declare number twice
        // also you're not summing up the entered numbers anywhere
        var number = prompt("Please Enter a Number");
        var number = parseInt(number);
        i++;

        document.write("Number: " + number);
        document.write("<br>");

    }
    while (i < 5);
}
show_prompt();
// number is out of scope of function show_prompt, hence undefined
var avrg = number + number + number + number + number
// to get an average, divide the sum by the total count of numbers
document.write('Average of scores : ' + avrg);

Answer №2

Take note that the variable "number" is only accessible within the `show_prompt()` function and cannot be accessed outside of it.

To calculate the average, you should modify your `show_prompt` function so that it doesn't loop but rather returns the number. Additionally, create another function that calls `show_prompt` multiple times and calculates the average based on the returned values. Currently, your code calculates the sum, not the average.

I won't provide the exact code, but here's a general idea:

calculate_average:
  var sum = 0;
  repeat 5 times:
    sum = sum + show_prompt();
  average = sum / 5;

show_prompt:
  var number = prompt('Enter a number');
  return number

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interested in learning how to code games using JavaScript?

Hi everyone, I'm currently exploring the world of Javascript and have been tasked with completing a game for a class project. The game involves a truck that must catch falling kiwis while only being able to move left or right. A timer is set for two m ...

What is the method to combine multiple style values in vue.js?

Is there a way to create a div with a box shadow where the values can be changed using a slider? I am having trouble using more than one value stored in a data variable. Any suggestions on how to achieve this? <div :style="{ borderRadius: x_axis y_ ...

Include certain tags to the content within the text apart from using bbcode tags

I need help with a project involving a BBCODE editor that can switch between a WYSIWYG editor and a code editor. The visual editor is designed with a drag-and-drop block system for elements like pictures and text. In the visual editor, when a user drags ...

Having trouble removing or adding a class to an HTML element?

I have a collection of three colored buttons. My goal is to allow users to select one button at a time, triggering it to be highlighted while the others are unselected. Each button corresponds to an object with a property called isSelected that can be set ...

The (window).keyup() function fails to trigger after launching a video within an iframe

Here is a code snippet that I am using: $(window).keyup(function(event) { console.log('hello'); }); The above code works perfectly on the page. However, when I try to open a full view in a video iframe from the same page, the ke ...

The delete_node() function in jstree does not seem to be removing nodes

In my attempt to create a custom context menu for different nodes, I've managed to display different labels for clicks on folders or files. However, I am facing some challenges when trying to delete them. Take a look at my code snippet. Due to diffic ...

Utilizing middleware with express in the proper manner

Hello there! I'm just double-checking to see if I am using the correct method for implementing middleware in my simple express app. Specifically, I am trying to ensure that the email entered during registration is unique. Here's an example of wha ...

Mask the "null" data in JSON

I'm currently working with a JSON file and trying to display it in a bootstrap table. Check out the code snippet I've been using: $(document).ready(function(){ $.getJSON(url, function(data){ content = '<h1><p class="p1 ...

Exploring the intersection of JavaScript and PostgreSQL: Leveraging timezones and timestamps

I'm a bit confused about how to properly use timestamps. For example, when a user creates an article, they can choose a PublishDate, and the system also automatically stores a CreateDate. a. Should I make both PublishDate and CreateDate timestamps wi ...

Error encountered when accessing JSON data from the DBpedia server in JavaScript

Hello everyone and thank you for your help in advance. I have encountered this error: Uncaught SyntaxError: Unexpected identifier on line 65 (the line with the "Var query", which is the third line) and when I click on the Execute button, I get another e ...

Ensure that the initial section of the page spans the full height of the browser, while all subsequent sections have a

I have a website composed of various blocks with different heights, all extending to full width. My goal is to make the first block the full height and width of the browser window, while keeping the other blocks at a set height as seen on this site: After ...

Is it possible to incorporate a combination of es5 and es2015 features in an AngularJS application?

In my workplace, we have a large AngularJS application written in ES5 that is scheduled for migration soon. Rather than jumping straight to a new JS framework like Angular 2+ or React, I am considering taking the first step by migrating the current app to ...

Guide on integrating a custom language parser and syntax validation into Monaco editor

I am in need of guidance on how to define a custom language in the Monaco editor. Despite my efforts, I have been unable to locate a reliable source for this documentation. My goal is to create a language with syntax similar to JavaScript, enabling users ...

Persisting a single module using vuex-persistedstate

Is there a way to configure vuex-persistedstate so that only one module persists state through page refresh? Currently, when I use plugins: [createPersistedState()] inside the user module, it does not work. plugins: [createPersistedState()] only works wh ...

What is the best way to show a nested div element within a v-for loop in Vue.js?

One interesting feature of my coding project is that I have an array nested within another array, and I iterate through them using two v-for loops. The challenge arises when I try to display a specific div in the second loop only upon clicking a button. ...

An error of type 'TypeError' has occurred, where it is unable to access the property 'render' of an undefined element in

I'm using a function in my controller to render the "result" in my "home-page" view, which is calling my model to execute the query. exports.searchNoms = (req, res) => { getDatabaseModel.searchNoms(req).then(function(result) { console.l ...

Unlock the potential of AngularJS services with this innovative design strategy

I am currently developing an AngularJS client application that will communicate with a REST server. To handle the interaction between the client and server, I have decided to use the $resource abstraction from AngularJS. Each resource is being written as ...

What is the best way to filter out empty arrays when executing a multiple get request in MongoDB containing a mix of strings and numbers?

I am currently working on a solution that involves the following code: export const ProductsByFilter = async (req, res) => { const {a, b, c} = req.query let query = {} if (a) { query.a = a; } if (b) { query.b = b; } if (c) { ...

Is the Okta SDK compatible with all identity providers?

I am looking to incorporate a wide range of Identity providers into my app, such as Auth0 SSO OIDC, Onelogin SSO OIDC, Google SSO OIDC, and others. Is it possible to use this solution to make that happen? https://github.com/okta/okta-auth-js ...

Invoke a PHP function located in a separate file using a JavaScript function to fetch data from a database

How can I properly call a PHP function from a JavaScript function located in a different file? I am trying to pass a variable from an onClick function in JavaScript to a PHP function, which will then access a MySQL database to retrieve data. However, my c ...