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

Loading images efficiently using JavaScript

While working on my JavaScript exercises, I encountered something strange with the image slider script I was creating. When trying to change the image source using the 'setAttribute' method in the HTML code, I noticed that the source of the imag ...

Exploring the concept of 'JavaScript with Scope' within the MongoDB environment

Within the link provided at https://docs.mongodb.com/manual/reference/bson-types/, it discusses JavaScript with Scope as a potential data type found in documents. I have some inquiries: (1) Could you explain what exactly JavaScript with scope entails? ( ...

Is the window frozen while Ajax processes the request?

When I make an ajax request that may take a significant amount of time to process on the server-side, I want to display a loading image during the request. However, the loading image is not showing up while the ajax request is processing. var ref = create ...

Connecting Angularfire2 with Firestore for advanced querying

Glad you stopped by! Currently, I have two Firestore Collections set up in my Angularfire2 application. One consists of "Clients", while the other contains "Jobs". Each client can have multiple jobs assigned to them, and vice versa. I've been workin ...

After logging out, Next-auth redirects me straight back to the dashboard

In my NextJS application, I've implemented a credential-based authentication flow along with a dashboard page. To handle cases where an unauthorized user lands on the dashboard route, I've created a custom AccessDenied component. In the getServer ...

JavaScript stylesheet library

What is the top choice for an open-source JavaScript CSS framework to use? ...

Styling for older versions of Internet Explorer (IE10 and earlier)

Could it be true that IE 10, 9, and others no longer support conditional statements? Is it also accurate to say that JQuery does not support the browser object above version 1.9? I am facing an issue with CSS rendering differently in Chrome and IE. A Goog ...

Exploring a JavaScript object to verify if a property contains nested data elements

I am currently working on traversing through the object above in order to determine if a contact is a member of a specific list. For instance, if the user is a member of the list with an ID of 2022, I want to display their first name (which is also includ ...

Encountering an error in a React application with Redux: "Unable to access the 'state' property of undefined"

I'm currently working on a react redux application where I want to add a message to the message array in the reducer's initial state when the add message button is pressed. However, I encountered an error "TypeError: newstate1.user.id.find is not ...

What steps should I take to establish routes in my node and express application that allow for authentication through a designated method?

Currently, I am following the backend set up tutorial from auth0, and I have a question regarding how to organize my routes in a separate file rather than in the app.js. In the tutorial, they demonstrate var authenticate = jwt({ secret: new Buffer(proc ...

Setting a port in Next.js: A step-by-step guide

I have one application currently running on port 3000 and I need to run another application on a different port in React Next.js. How can I make this change? In my package.json file, the current scripts section looks like this: "scripts": { & ...

Selecting Objects with a Mouse in Three.js

Thanks to the wonderful support from the stackoverflow community, I was able to successfully implement a basic object picking example. You can view the functional code here. However, it's important to note that this example specifically works when t ...

Triggering an event from a component to its parent module resulting in an exception situation

Here is my app.component.ts code: import { Component, Input, OnInit, OnChanges, SimpleChanges} from '@angular/core'; import {Counter } from './counter' @Component({ selector: 'my-app', template: ` <custom-counter [ ...

Issues with AJAX formData functionality

I'm having difficulties with the formData in my Ajax calls. I have searched extensively for solutions and tried various approaches, including using getElementById, but nothing seems to work. The form in question has an id of add-lang-form: <form ...

Maintaining datatype integrity in MongoDB Stitch when decrementing with update statements

Using a MongoDB Stitch function, I have two collections: communities and posts. Whenever a new document is inserted in the post collection, I need to increment the summary.postCount in the communities collection by +1. Similarly, when the status of a post ...

Issue with updating nested child object reference in Redux state input value

I have a function in redux that updates an object with a specified path and value. The inputs on my page are based on the values in the object stored in state. Whenever the listingObj is modified in redux, I want the DOM to automatically refresh. This i ...

Can you explain the variance in these code snippets when implementing React's setState() function?

Can you explain the variance between these two blocks of code? this.setState((state)=>({ posts: state.posts.filter(post=> post.id !==postRemoved.id) })) versus this.setState((state)=>{ posts: state.post ...

Fluid Grid System with columns of specific dimensions

Recently delving into the world of Foundation Framework, I've just begun utilizing it for my projects. My current task involves crafting a responsive design with the help of the Foundation Grid system. Specifically, I've set up a grid layout for ...

Gaining entry into a JSON object

I'm currently working on a web page that utilizes API data from the Breaking Bad website. I have received this data in JSON format, but I am struggling to figure out how to access only the objects where the "author" is "Walter White." Here is the data ...

What is the best way to dynamically insert an email value into a JSON file?

Here is the structure of my JSON file: test.json: { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3b8a1baa093beb2babfbabdb2a7bca1fdb0bcbe">[email protected]</a>", "password": "Sanju@143", ...