1.I include what the two lines i want to combine in the first comment of the code. If you can point me to what i need to do it would really help. I just started javascript a couple days ago. If u can recommend any books please tell me. im currently reading the murach series of books and its really helping.
/*The two statements i want to combine are
entry = parseInt(entry);
var score1 = entry; */
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Average Test Scores</title>
<script>
var entry;
var average;
var total = 0;
//get 3 scores from user and add them together
entry = prompt("Enter test score");
entry = parseInt(entry);
var score1 = entry;
total = total + score1;
entry = prompt("Enter test score");
entry = parseInt(entry);
var score2;
total = total + score2;
entry = prompt("Enter test score");
entry = parseInt(entry);
var score3 = entry;
total = total + score3;
//calculate the average
average = parseInt(total/3);
</script>
</head>
<body>
<script>
document.write("<h1>The Test Scores App</h1>");
document.write("Score 1 = " + score1 + "<br>" +
"Score 2 = " + score2 + "<br>" +
"Score 3 = " + score3 + "<br><br>" +
"Average score = " + average + "<br><br>");
</script>
Thanks for using the Test Scores application!
</body>
</html>
Addition assignment, The addition assignment operator adds the value of the right operand to a variable and assigns the result to the variable.
Unary plus (+), The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.
Simplified version:
var total = 0;
var score1 = +prompt("Enter test score"); //Cast it to Number
total += score1; //Add it to total
var score2 = +prompt("Enter test score");
total += score2;
var score3 = +prompt("Enter test score");
total += score3;
var average = parseInt(total / 3);
document.write("<h1>The Test Scores App</h1>");
document.write("Score 1 = " + score1 + "<br>" +
"Score 2 = " + score2 + "<br>" +
"Score 3 = " + score3 + "<br><br>" +
"Average score = " + average + "<br><br>");
Related
I'm taking a class on computer programming, and I have an assignment where I have to make a loop in which users enter data into a prompt, and at the end I will output the lowest, highest, average, and total of that data. The problem is, I can't figure out how to have that data stored as different values every time. Btw I'm using javascript, and the project has to be done with that language.
var g = 1;
var points = alert("Please enter the scores of the player in the prompts.");
var totalPoints = 0;
do {
var pointsCount = Number(prompt("Please enter how many points the user entered in Game " + g + ":"))
i++
g++
totalPoints += pointsCount
} while (pointsCount != -1)
alert("*** Your Player Stats *** /n" + " Minimum points: " + Math.min(pointsCount) + " Maximum points: " + Math.max(pointsCount) + " Average points: " + totalPoints/i + " Total points: " + totalPoints);*```
I would store data outside the loop and update it when needed. You don't have i varaible in your code. You can use here a while loop with true condition so it repeats infinitely, and break out of it using some condition (e.g. -1 as input). Take a look at the code below.
let totalPoints = 0;
let minPoints;
let maxPoints;
let numberOfGames = 0;
while(true){
let points = Number(prompt("Please enter how many points for this game"))
// skip invalid data
if(isNaN(points)){
continue;
}
// loop exit condition
if(points === -1) break;
// set min if not undefined or lower than recorded
if(!minPoints || points < minPoints){
minPoints = points;
}
// same as above but for max
if(!maxPoints || points > maxPoints){
maxPoints = points;
}
totalPoints += points;
numberOfGames++;
}
alert("*** Your Player Stats ***" + "\nMinimum points: " + minPoints + "\nMaximum points: " + maxPoints + "\nAverage points: " + totalPoints/numberOfGames + "\nTotal points: " + totalPoints);
This question already has answers here:
Javascript (+) sign concatenates instead of giving sum of variables
(14 answers)
Closed 11 months ago.
The parseInt(sum3) + parseInt(sum5) is not adding the two variables. It just concatenates them. How can I add the two?
I know I can just manually create another variable and put the output of sum3 there and put the output of sum5 in another variable and add them like that but I idk I think that's cheating. So how can I add the sum3 and sum5?
// sum of 3
let max3 = parseInt(1000);
let sum3 = 0;
for ( let three=3; three<=max3; three++ ){
sum3+=three
}
// sum of 5
let max5 = parseInt(1000);
let sum5 = 0
for (let five=5; five<=max5; five++){
sum5+=five
}
// sum of 3 and 5
document.write("Sum of 3 = " + sum3 + "<br/>"
+ "Sum of 5 = " + sum5 + "<br/>" +
"Sum of 3 and 5 = " + parseInt(sum3) + parseInt(sum5));
It's just because you're using + in the context of string concatenation.
Should be:
document.write("Sum of 3 = " + sum3 + "<br/>"
+ "Sum of 5 = " + sum5 + "<br/>" +
"Sum of 3 and 5 = " + (sum3 + sum5));
Or you really should use:
document.write(`Sum of 3 = ${sum3} <br/>
Sum of 5 = ${sum5} <br/>
Sum of 3 and 5 = ${sum3 + sum5}`);
You can just wrap parseInt(sum3) + parseInt(sum5) in a () bracket and it should do the job.
// sum of 3
let max3 = parseInt(1000);
let sum3 = 0;
for (let three = 3; three <= max3; three++) {
sum3 += three
}
// sum of 5
let max5 = parseInt(1000);
let sum5 = 0
for (let five = 5; five <= max5; five++) {
sum5 += five
}
// sum of 3 and 5
document.write("Sum of 3 = " + sum3 + "<br/>" +
"Sum of 5 = " + sum5 + "<br/>" +
"Sum of 3 and 5 = " + (parseInt(sum3) + parseInt(sum5)));
You concatenate both string values with the use of '+'.
Don't combine this with string so '+' will still work as expected.
// sum of 3
let max3 = 1000;
let sum3 = 0;
for (let three=3; three<=max3; three++){
sum3+=three
}
// sum of 5
let max5 = 1000;
let sum5 = 0
for (let five=5; five<=max5; five++){
sum5+=five
}
// sum of 3 and 5
let totalSum = sum3 + sum5
document.write("Sum of 3 = " + sum3 + "<br/>"
+ "Sum of 5 = " + sum5 + "<br/>" +
"Sum of 3 and 5 = " + totalSum);
Ask user to enter a number. Then ask the user to enter a number bigger than the first number. Calculate a value that is the sum of all the numbers from the first number to the second number including the end points. For example, if the user enters 5 and 10 then calculate the total of 5 + 6 + 7 + 8 + 9 + 10. Display the results. MUST USE A WHILE LOOP
This is what I have so far. I can't seem to get the sum to be correct. If I enter the numbers from the example above, I get 49 instead of 45. I understand where I went wrong and why it is 49 based on my code but can't figure out how to make it correct.
// declare constants
const INITIAL_VALUE = 0;
const COUNTER_VALUE = 1;
// declare variables
var number1;
var number2;
var sum;
var counter;
var difference;
var middlePoint;
var middlePointSum;
// assigning values
sum = INITIAL_VALUE;
difference = INITIAL_VALUE;
counter = COUNTER_VALUE;
middlePoint = COUNTER_VALUE;
middlePointSum = INITIAL_VALUE;
// prompt user to enter two numbers
number1 = prompt("Enter first number: ");
number2 = prompt("Enter a number bigger than first number: ");
// convert user input into numbers
number1 = Number(number1);
number2 = Number(number2);
// display number1
document.write(number1);
difference = number2 - number1;
middlePoint += number1;
while (counter < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1;
counter++;
middlePointSum += middlePoint;
}
// calculate the sum
sum = number1 + middlePointSum + number2;
// display number1, middle points, number2, and sum
document.write(" + " + number2 + " = " + sum);
// prompt user to enter two numbers
var number1 = prompt("Enter first number: ");
var number2 = prompt("Enter a number bigger than first number: ");
// convert user input into numbers
var number1 = Number(number1);
var number2 = Number(number2);
var start_point= number1;
var sum=0;
// display number1
document.write(start_point);
sum += start_point;
start_point++;
while (start_point <=number2) {
document.write(" + " + start_point);
sum += start_point;
start_point++;
}
// display sum
document.write(" = " + sum);
Welcome to StackOverflow!
The cause of error is at this part of the code
while (counter < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1; // you are already increasing the middlePoint number
counter++;
middlePointSum += middlePoint;
}
Therefore, the sum is always over by the number of counter - 1. What you should have done, is execute middlePointSum += middlePoint; first before increasing the value of middlePoint and counter.
while (counter < difference) {
document.write(" + " + middlePoint);
middlePointSum += middlePoint;
middlePoint = middlePoint + 1;
counter++;
}
This code should work for you. Variabel sum should contain your desired sum.
var sum = 0;
var firstNumber = 0;
var secondNUmber = 0;
var firstNumberStr = '';
var secondNUmberStr = '';
// prompt user to enter two numbers
firstNumberStr = prompt("Enter first number: ");
while(isNaN(firstNumberStr)){
firstNumberStr = prompt("Enter Correct first number: ");
}
secondNUmberStr = prompt("Enter a number bigger than first number: ");
while(isNaN(secondNUmberStr) || parseInt(firstNumberStr) >= parseInt(secondNUmberStr)){
secondNUmberStr = prompt("Enter a number bigger than first number: ");
}
firstNumber = parseInt(firstNumberStr);
secondNUmber = parseInt(secondNUmberStr);
while(firstNumber <= secondNUmber){
sum += firstNumber;
firstNumber++
}
You did a very small mistake in the code . The bug is in while loop.
while (counter < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1;
counter++;
middlePointSum += middlePoint;
}
you are incrementing the middlepoint before middlePointSum is Calculated. It should be incremented after calculating the middlePointSum.
while (counter < difference) {
document.write(" + " + middlePoint);
counter++;
middlePointSum += middlePoint;
middlePoint = middlePoint + 1;
}
Your middlePointSum is starting from 1 intead of 0 so you got: 5 + (7 + 8 + 9 + 10) + 10 to fix your code set middlePointSum to INITIAL_VALUE
For simplification just ignore the difference between the numbers, increment number1 until you reach number 2
var number1 = prompt("Enter first number: ");
var number2 = prompt("Enter a number bigger than first number: ");
var incNumber;
var strResult = [];
number1 = incNumber = Number(number1);
// use incNumber if you need to preserve number1 value or just use number 1 value instead
number2 = Number(number2);
var sum = 0;
while(incNumber <= number2) {
strResult.push(incNumber);
sum += incNumber++;
// this means add incNumber to sum then increment it by 1
}
document.write(`${strResult.join(' + ')} = ${sum}`);
One problem is that your middlePointSum does not take into account the first number after the number1, for example, the 6 in your example. Another problem is that your counter < difference test is inaccurate - you would have to iterate until counter + 1 < difference:
// declare constants
const INITIAL_VALUE = 0;
const COUNTER_VALUE = 1;
// declare variables
var number1;
var number2;
var sum;
var counter;
var difference;
var middlePoint;
var middlePointSum;
// assigning values
sum = INITIAL_VALUE;
difference = INITIAL_VALUE;
counter = COUNTER_VALUE;
middlePoint = COUNTER_VALUE;
middlePointSum = INITIAL_VALUE;
// prompt user to enter two numbers
number1 = prompt("Enter first number: ");
number2 = prompt("Enter a number bigger than first number: ");
// convert user input into numbers
number1 = Number(number1);
number2 = Number(number2);
// display number1
document.write(number1);
difference = number2 - number1;
middlePoint += number1;
middlePointSum = middlePoint;
while (counter + 1 < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1;
counter++;
console.log(middlePointSum);
middlePointSum += middlePoint;
}
// calculate the sum
sum = number1 + middlePointSum + number2;
// display number1, middle points, number2, and sum
document.write(" + " + number2 + " = " + sum);
But this seems far, far more complicated than it needs to be - why not simply iterate from number1 to number2, adding to sum along the way?
const number1 = Number(prompt("Enter first number: "));
const number2 = Number(prompt("Enter a number bigger than first number: "));
document.write(number1);
let sum = number1;
for (let i = number1 + 1; i <= number2; i++) {
sum += i;
document.write(' + ' + i);
}
document.write(' = ' + sum);
Or, create an array of the numbers, join by plus signs, and calculate the sum with reduce:
const number1 = Number(prompt("Enter first number: "));
const number2 = Number(prompt("Enter a number bigger than first number: "));
const nums = Array.from(
{ length: number2 - number1 + 1 },
(_, i) => i + number1
);
const sum = nums.reduce((a, b) => a + b);
document.write(nums.join(' + ') + ' = ' + sum);
var num1 = Number(prompt("Enter a number"));
var num2 = Number(prompt("Enter a larger number"));
document.write(num1 + "+" + num2 + "=" + (num1+num2));
// now lets find the sum of numbers between these two numbers.
document.write("<br>"); // new line
var counter = num1; // we will start countring from the smaller number
var sum = 0;
//keep looping until we reach the bigger number (num2)
while(counter<=num2) {
sum += counter;
// print the current number
document.write(counter);
//print a plus sign
if(counter<num2) {
// only put a (plus sign) if we are not yet reached num2
document.write("+");
}
//increment to control the loop
counter ++;
}
//finally put the result
document.write("=" + sum);
You are setting counter to the constant COUNTER_VALUE which is 1.
Then, in your program, you are entering 5 and 6 as input. The difference is 6-5 which is 1.
Your while loop has a condition to only execute when counter<difference . In your case, counter=1 and difference=1. This means that they are equal, and thus, the loop will not execute.
I hope this sheds light on what needs to be done from your side to fix this bug.
I'm trying to solve the following Kata:
a 2 digit number, if you add the digits together, multiply by 3, add 45 and reverse.
I'm unable to figure out how to return the data from my function so that I can later assign the value to an HTML element.
This is my code.
function daily() {
for(var j = 10; j < 100; j++) {
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
}
} else {
console.log("Not a 2 digit Number!!");
}
}
teaser(j);
}
}
From your question I'm guessing you need reversal value on function daily for loop.
Would recommend you to take out function teaser from inside for-loop, this will make code much cleaner and easy to understand and you can do like:
function daily() {
for(var j = 10; j < 100; j++) {
var teaser = teaser(j);
// Can now use anything returned from teaser function here
}
}
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
return reversal;
}
} else {
console.log("Not a 2 digit Number!!");
return false;
}
}
If don't want to take function out then you can do this:
function daily() {
for(var j = 10; j < 100; j++) {
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
return reversal;
}
} else {
console.log("Not a 2 digit Number!!");
return false;
}
}
var teaser = teaser(j);
// Can now use anything returned from teaser function here
}
}
Returning something from a function is very simple!
Just add the return statement to your function.
function sayHello(name) {
return 'Hello ' + name + '!';
}
console.log(sayHello('David'));
okay, so my issue has been solved! Thanks all of you, especially krillgar, so I had to alter the code you gave me krillgar, a little bit in order to populate the results array with only the numbers (one number in this case) that satisfy the parameters of the daily tease I was asking about. yours was populating with 89 undefined and on number, 27 because it is the only number that works.
One of my problems was that I was expecting the return statement to not only save a value, but also show it on the screen, but what I was not realizing was that I needed a place to store the value. In your code you created a result array to populate with the correct numbers. And also, I needed a variable to store the data for each iteration of the for loop cycling through 10 - 100. Anyways, you gave me what I needed to figure this out and make it do what I wanted it to do, and all is well in the world again.
Anyway, thank you all for your help and input, and I will always remember to make sure I have somewhere to store the answers, and also somewheres to store the value of each loop iteration in order to decide which numbers to push into the results array and save it so it can be displayed and/or manipulated for whatever purpose it may be. I guess I was just so busy thinking about the fact that when I returned num it didn't show the value, instead of thinking about the fact that I needed to store the value. Here is the final code for this problem and thanks again peoples!
function daily() {
var results = [];
for(var j = 10; j < 100; j++) {
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
return num;
// Here you have one that is correct, so return it:
} else {
console.log(num + " does not fulfill function parameters");
// This is just so you can visualize the numbers
return null;
}
}
}
var answer = teaser(j);
if(answer != null) {
results.push(answer);
}
}
return results;
}
As was said in the comments of the question, because you're going to (most likely) have multiple answers that match your condition, you will need to store those in an array. Your teaser function returns individual results, where daily will check all the numbers in your range.
function daily() {
var results = [];
for(var j = 10; j < 100; j++) {
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
// Here you have one that is correct, so return it:
return num;
} else {
// Make sure we don't return undefined for when the sum
// times three doesn't equal the number.
return null;
}
} else {
console.log("Not a 2 digit Number!!");
return null;
}
}
var answer = teaser(j);
if (answer !== null) {
results.push(answer);
}
}
return results;
}
I am having an issue with getting the average of the numbers that are inputted through a prompt window. I need to display the numbers like i have so far, but I can't seem to get them to add together to get the average.
here is my code so far.
<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>
You have to move calculation inside function. Also you can do it simplier:
function show_prompt() {
var i = 0;
var sum = 0;//declare a variable to keep the sum of numbers
do {
var number = prompt("Please Enter a Number");
sum += parseInt(number); //sum the numbers here
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
document.write('Average of scores : ' + sum / i);//use the sum of the numbers divide by the the numbers the user enters
}
show_prompt();
Tried to comment your old code with the mistakes:
function show_prompt() {
i = 0;
do {
//there is no need to declare number twice
//also you don't sum somewhere the numbers you get from the user
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 so is undefined
var avrg = number + number + number + number + number
//to get an avg you have to divide the sum by the number
document.write('Average of scores : ' + avrg);
Notice your var number is scoped within show_prompt(), it is not visible outside of it.
You need to have your show_prompt function not loop, and return the number, and have another function that calls show_prompt multiple times, takes the returns and calculate the average.. Also, your code is just calculating the sum, not the average
I'm not going to show you the exact code, but here's the idea
calc_average:
var sum=0;
loop 5 times:
sum = sum + show_prompt();
average = sum/5;
show_prompt:
var number = prompt('blah blah');
return number