Javascript - Calculate average of numbers - javascript

pretty new here and in programming overall so I would really appreciate some help.
Now, I want to create a site that has a button which calls a function when clicked. This function brings up a prompt box that allows the user to insert numbers only, infinitely or until he clicks cancel on the prompt box or presses space.
When the insertion of the numbers has stopped, the function calculates the average of all the numbers inserted and displays the result on an alert box. I have tried it and here's my code so far.
<html>
<head>
<script type="text/javascript">
function calc_avg() {
var avg; var sum;var total;var num=1;
while (num>0) {
var x = parseInt(prompt("Please enter a number","0"))
if (x=="") {
break;
} else {
sum += x;
total++;
avg=sum/total;
window.alert(avg);
}
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="calc_avg()" value="Calculate Average">
</form>
</body>
</html>
Thanks in advance!

Related

Run a loop n times

I'm writing a program that will calculate a number entered by the user multiplied by 2.
I realised I need a for loop so that the Value will increment by 1 and multiple by 2
The problem is I want to know how to run this loop only 10 times
- at the current moment it will run for ever and I had to place an if statement to break out of the loop if the value reaches 50.
//prompt user to enter number
let value = prompt("Enter A number");
//user entered number will loop through while output will show multiples //of 2
for (value;; value++) {
value2 = value * 2;
document.write(`${value} multiply 2 -> ${value2}`);
document.write('<br>');
//i placed this if statement to break out of the for loop as it //will run forever
if (value > 50) {
break;
}
}
you can use a counter variable to keep a check on number of iterations. I am guessing you want to increase value by 1 after each iteration. You can do something like this:
//prompt user to enter number
let value = prompt("Enter A number");
//user entered number will loop through while output will show multiples //of 2
for (var i=1;i<=10; i++) {
value2 = value * 2;
document.write(`${value} multiply 2 -> ${value2}`);
document.write('<br>');
//i placed this if statement to break out of the for loop as it //will run forever
value++;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--
<script type="text/javascript" src="js.js"></script>
-->
</head>
<body></body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Multiple By 2</h2>
<input type="text" id="num"/>
<button onclick="multiply()">multiply by 2</button>
<script>
function multiply() {
var number = document.getElementById("num").value;
for(i=1;i<11;i++){
console.log(number*i);
}
}
</script>
</body>
</html>

Javascript Exponents in HTML

I need to create a JavaScript function that uses input=number to pass it to a JavaScript function to raise it to 2nd, 3rd, 4th, and 5th powers. So far I can pass a number to it and out put that number, but can not seem to grasp the math.pow and also how to get all the other powers. Here is what I have so far.
<!DOCTYPE html>
<html>
<body>
<h1>Opponents!? More Like Ex-Ponents</h1>
<input type="number" id="myNumber" value="0">
<p>Click the button to get the exponents of the number field.</p>
<button onclick="myFunction()">Calculate</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
I'm not able to just input values. I need to be able to take a value that was input by the user and do the calculations on it. I've tried this with little results.
<script>
function myFunction() {
var x = document.getElementById("myNumber").value;
var y = math.pow(x,2);
document.getElementById("demo").innerHTML = y;
}
</script>
Math.pow works like so:
Math.pow(value, exponent)
so if I wanted to raise 5 by 11 I would do:
Math.pow(5,11)
Just replace the numbers with the variables you're using for value and exponent

Generating a random number in JavaScript

All I'm trying to do is have the user click a button to generate a random number. It seems to work, but the number only displays for a second before disappearing.
Here is my code.
<!DOCTYPE html>
<head>
</head>
<body>
<h3>
This is a random number generator!
</h3>
<form onsubmit= "randomNumber()">
<input type="submit" value="Click me!">
</form>
<script>
function randomNumber() {
document.write(Math.floor(Math.random() * 10));
}
</script>
<p id="number">
</p>
</body>
</html>
You need
<form onsubmit="randomNumber(); return false;">
to prevent a new load of the page and
function randomNumber() {
document.getElementById('number').innerHTML = Math.floor(Math.random() * 10);
}
to set the value.
Nina's answer is good, but you don't really need a form for that. How about this instead of your form?
<button onclick="randomNumber()">Click me!</button>
Then the randomNumber function would go as Nina suggested:
function randomNumber() {
document.getElementById('number').innerText = Math.floor(Math.random() * 10);
}
Since there is no form, there's no need to prevent the form from actually being sent.
Incidentally, this would put the random number in the p with id "number", which I guess is what you wanted. However, if you want to leave a page which contains just the number, use document.write instead of document.getElementById..., as in your original snippet.

Javascript Random Number Generator comes up with NaN

I am trying to make a random number generator using a form. When you press the button, and enter in the maximum number, it comes up with a dialog box reading NaN, when it is meant to come up with the random number.
I have some code that looks like this:
<html>
<head>
</head>
<body>
<form name="gen">
<h1>Random Number Generator</h1>
<b>Number:</b> 1 to
<input id="numgen" type="text"/>
<button name="generate" type="submit" onclick="gennum()">Generate!</button>
<script>
function gennum()
{
alert(Math.floor(Math.random() * num.value + 1));
}
var num = document.getElementById('numgen').value;
</script>
</form>
</body>
</html>
I am not very good with Javascript, but I know a bit. If anyone knows how to fix this, I would be happy.
num.value is a string. Use parseInt(num.value, 10) to turn it into a number, that way it can be added to a number appropriately.
Also, it looks like you're getting the value twice, and the first time is when the page loads (so it doesn't have a value yet:
var numElem = document.getElementById('numgen'); //remove value here
then in your function:
alert(Math.floor(Math.random() * parseInt(num.value + 1)));
and, you need to use type="button" on your button, or the page will reload.
Here's your code refactored with better practices.
Live demo here (click).
Markup:
<form name="gen">
<h1>Random Number Generator</h1>
<b>Number:</b> 1 to
<input id="numgen" type="text"/>
<button id="generate" type="button">Generate</button>
</form>
JavaScript:
/* get element references */
var genButton = document.getElementById('generate');
var numInput = document.getElementById('numgen');
//use javascript to add the click function
genButton.addEventListener('click', function() {
/* it's easier to read and debug if you break things up
* instead of putting it all on one line with tons of ((()))
*/
var rand = genRandom(1, parseInt(numInput.value, 10));
alert(rand);
});
function genRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

JavaScript beginner: How to restart a loop

Once the user guesses the right number I need to ask if the user would like to play again. As it is the loop will just repeat itself but what I need is the prompt box to ask if you would like to play again. If the user replies yes the loop will initiate again until the answer is guessed
<HTML>
<HEAD>
</HEAD>
<BODY
<FORM NAME="testform">
<BR>
<BR>
<BR>
</FORM>
<INPUT id="attempts" TYPE="text" NAME="inputbox" VALUE="" />
<INPUT id="zero" TYPE="button" NAME="resetbox" VALUE="Reset " onclick="reset()" />
<SCRIPT type="text/javascript">
varattempts = 0;
x = Math.round((Math.random()*19))+1;
var tip;
tip=prompt("Do you want to play a game?")
while(tip.charAt(0).toLowerCase() == "y")
{
var Guess;
document.getElementById('attempts').value = 0;
do
{
Guess = prompt("Pick a number between 1 and 20","")
if (Guess === null) break;
document.getElementById('attempts').value = parseInt(document.getElementById('attempts').value)+1
} while (Guess!=x);
if (Guess == x)
{
alert("You guessed right!")
}
}
function reset()
{
varattempts=0;
document.getElementById('attempts').value = 'Attempts: 0';
}
</SCRIPT>
</BODY>
</HTML>
Put your loop inside another loop. Loopedy loop dee doop.
Easiest it to create a function for running an iteration. When that iteration finishes, the function returns and you ask if they want to play again. If so, you call the function again.
Put all your other code in a function named play():
function play() {
// all your other code here
}
// Then call that function in a loop, return true from play() if the user is done
// and doesn't wish to be asked if they want to play again
var done;
do {
done = play();
} while (!done || window.confirm("Do you want to play again?"));
you could put the main bit in a function, then when its time to reset, return false and recall the function depending on the prompt box. if its yes call it if not just do nothing or maybe display some different text?
varattempts = 0;
looks like a mistake
looks like a messed up way to write something simple imo.

Categories