I have been working on a maths project for my son, and am currently struggling to attach the correct maths sum to the correct math operator currently shown on the website.
The function mathOperator() aims to identify what math operator is currently on page and then supply the correct sum.
Then i am trying to check if the textContent of the chosen clicked answer matches that sum or not using the anonymous function below mathOpertor().
I am getting no errors in the console but the code is annoyingly just adding num1 and num2 together no mater which math operator is currently active.
I figure the problem is within the lines:
let operator = num1 + num2;
if (this.textContent == operator) { }
I figured (let operator) would be mutated to the condition that was met within the mathOperator() function, but this is not the case!
Here is my code below:
//Globals
const arrLength = 10
const randomArr = []
//push random numbers to randomArr.
for (let i=0; i<arrLength; i++) {
randomArr.push(Math.floor(Math.random() * 10));
}
//DOM targets
//first and second numbers.
const num1 = document.getElementById("num1").textContent = randomArr[0];
const num2 = document.getElementById("num2").textContent = randomArr[1];
//Multiple choice answers
let option1 = document.getElementById("option1").textContent = randomArr[2];
let option2 = document.getElementById("option2").textContent = randomArr[3];
let option3 = document.getElementById("option3").textContent = randomArr[4];
//Places the correct asnwer randomly within the 3 multiple choice answers.
const correctAnswerPosition = Math.floor(Math.random() * 3);
document.querySelectorAll(".options h1")[correctAnswerPosition].textContent = num1 + num2;
//function to decide how to calculate equation depending on what HTMLpage you are on.
function mathoperators(sum) {
if (document.querySelector(".wrapper div").children[1].textContent == "+") {
sum = num1 + num2;
} else if (document.querySelector(".wrapper div").children[1].textContent == "-") {
sum = num1 - num2;
} else if (document.querySelector(".wrapper div").children[1].textContent == "*") {
sum = num1 * num2;
} else if (document.querySelector(".wrapper div").children[1].textContent == "/") {
sum = num1 / num2;
}
}
//What do to if you pick right or wrong answer.
for (let a=0; a<document.querySelectorAll(".options").length; a++) {
//targets the 3 divs that contain random incorrect answers plus correct answer.
document.querySelectorAll(".options")[a].addEventListener("click", function() {
let operator = num1 + num2;
if (this.textContent == operator) { //problem here i don't know how to connect this to sum in math operators function.
const correct = new Audio("Sounds/correct.mp3");
correct.play();
document.querySelector(".wrapper").style.display="none";
document.querySelector(".well-done").style.display="block";
setTimeout(function() {
location.reload();
}, 3000);
} else {
const incorrect = new Audio("Sounds/incorrect.mp3");
incorrect.play();
}
mathoperators(operator)
})
}
function reload() {
reload = location.reload();
}
Thankyou for your time in advance.
# bergi, Thanks very much this is the push in the right direction I needed, the changes have been made below:
function mathoperators() {
if (document.querySelector(".wrapper div").children[1].textContent == "+") {
return num1 + num2;
} else if (document.querySelector(".wrapper div").children[1].textContent == "-") {
return num1 - num2;
} else if (document.querySelector(".wrapper div").children[1].textContent == "*") {
return num1 * num2;
} else if (document.querySelector(".wrapper div").children[1].textContent == "/") {
return num1 / num2;
}
}
//What do to if you pick right or wrong answer.
for (let a=0; a<document.querySelectorAll(".options").length; a++) {
document.querySelectorAll(".options")[a].addEventListener("click", function() {
const number = parseFloat(this.textContent)
if (mathoperators() === number) {
const correct = new Audio("Sounds/correct.mp3");
correct.play();
document.querySelector(".wrapper").style.display="none";
document.querySelector(".well-done").style.display="block";
After this I also noticed that the below needed changing so that it was equal to mathOperator() and not num1 + num2;.
//Places the correct asnwer randomy within the 3 multiple choice answers.
const correctAnswerPosition = Math.floor(Math.random() * 3);
document.querySelectorAll(".options h1")[correctAnswerPosition].textContent = mathoperators();
Thanks for your help Bergi.
ok so I have been going at it for a while im making a palindrome program on html for the first time but when I input 111 it says its not a palindrome even tho i went through the while loop with a calc and it should be the same. I checked the outputs by revealing em and
"input" = 111.
"temp" = 0 as it should.
"reversed" tho is equal to infinity lol and idk y any help is appreciated.
function Palindrome() {
let input = document.querySelector("#userInput").value;
var temp = input;
let reversed = 0;
while (temp > 0) {
const lastDigit = temp % 10;
reversed = (reversed * 10) + lastDigit;
temp = (temp / 10);
}
if (input == reversed) {
document.querySelector("#answer").innerHTML = `This is a Palindrome `;
}else {
document.querySelector("#answer").innerHTML = `This is not a Palindrome ${input} ${temp} ${reversed} `;
}
}
You're doing floating point division, so temp will never be more than 0 until you do many iterations and get floating point underflow. After each iteration it becomes 11.1, then 1.11, then 0.111, .0111, and so on. This is multiplying reversed by 10 each time, and it eventually overflows to infinity.
Round the number when dividing so that the fraction will be discarded:
temp = Math.round(temp / 10);
function Palindrome(input) {
var temp = input;
let reversed = 0;
while (temp > 0) {
const lastDigit = temp % 10;
reversed = (reversed * 10) + lastDigit;
temp = Math.round(temp / 10);
}
if (input == reversed) {
console.log(`This is a Palindrome ${input}`);
} else {
console.log(`This is not a Palindrome ${input} ${temp} ${reversed} `);
}
}
Palindrome(111);
Palindrome(123)
As Barmar explained in his answer about percent division try to git rid of it!
function Palindrome() {
let input = document.querySelector("#userInput").value;
//convert input to number
var temp = +input;//or parseInt(input)
let reversed = 0;
while (temp > 0) {
const lastDigit = temp % 10;
reversed = reversed * 10 + lastDigit;
temp = Math.floor(temp / 10);//<-- to prevent Infinity
}
if (input == reversed) {
document.querySelector("#answer").innerHTML = `This is a Palindrome `;
} else {
document.querySelector(
"#answer"
).innerHTML = `This is not a Palindrome ${input} ${temp} ${reversed} `;
}
}
<input type="input" value="" id="userInput">
<input type="button" value="Is Palindrom" onclick="Palindrome()">
<div id='answer'></div>
Quick follow-up question on my previous question. I'd like to add the code to the following to calculate the factorial of a number entered by user in Javascript.
<!DOCTYPE html>
<html>
<head>
<title>Sum of Numbers</title>
<script>
var numbers = prompt("Enter a number 1-100");
while (numbers!=null && (isNaN(parseInt(numbers)) || parseInt(numbers) >100 || parseInt(numbers) <1)) {
numbers = prompt("Try again.Enter a number 1-100");
}
if (numbers !=null){
alert("Finally you entered a correct number");
var sum = 0;
var numOfLoops = numbers;
var counter = 1;
do {
sum+=counter;
counter++;
}
while (counter<=numOfLoops)
alert ("The sum of numbers from 1 to " + numbers + "is =" +sum);
}
</script>
</head>
<body>
<script>
document.write("<h1>Sum of Numbers</h1>");
document.write("The sum of numbers from 1 to = " + numbers + " is = " +
+ sum + "<br><br>");
</script>
</body>
</html>
If you are trying to sum up the numbers, consider using arithmetic series formula. If you're trying to get the factorial, the approach is shown below.
If you want to sum using the loop, just change the *= to +=.
While Loop Approach
const fact = (n) => {
let res = 1;
while (n > 0) {
res *= n;
n--;
}
return res;
}
fact(5) // 120
Do While Approach
const fact = (n) => {
let res = 1;
do {
res *= n;
n--;
} while (n > 0)
return res;
}
fact(3) // 6
That should do the trick. :)
Maybe also considering checking for edge cases like if the n is negative.
Good luck.
While Loop:
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
while(n) r *= n--
return r
}
Do While:
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
do r *= n || 1 // in case of n == 0
while (n--)
return r;
}
complete code
const
msgPrompt_1 = 'Please enter a number from 0 to 100',
msgPrompt_n = 'Try again.... Enter a number 0-100',
fact = n =>
{
let r = 1
while(n) r *= n--
return r
}
let numValue = parseInt(window.prompt(msgPrompt_1, ''), 10)
while(isNaN(numValue) || numValue > 100 || numValue < 0)
{
numValue = parseInt(window.prompt(msgPrompt_n, ''), 10)
}
alert(`factorial value of ${numValue} is = ${fact(numValue)}` )
Here's the problem I'm trying to solve:
Write a program that asks a user to enters pairs of numbers until they enter "quit". As each pair of numbers is entered and validated, add the numbers using a function. The function will have two parameters for the pair of numbers and will return the sum. After the user enters "quit", output all the pairs of numbers and their sums.
I've got the program to output number1, number2 and the sum when I just do one, but when I try to repeat until the user enters "quit" I seem to break it?
//function to sum 2 entered numbers
function sum2enteredNumbers(number1, number2)
{
var sum1and2;
sum1and2 = number1 + number2;
return sum1and2;
}
function exercise4Part1() {
// PART 1: YOUR CODE STARTS AFTER THIS LINE
var QUIT_CODE = "quit";
var output;
var number1;
var number2;
while (number1 !== QUIT_CODE || number2 !== QUIT_CODE)
{
number1 = Number(prompt("Enter a number:"));
number2 = Number(prompt("Enter another number:"));
}
sum1and2 = sum2enteredNumbers(number1, number2);
output = document.getElementById('outputPart1');
output.innerHTML = "<br />Entry 1: " + number1 + " Entry 2: " + number2 + " Sum: " + sum1and2;
}
Attempt 2--still not working:
function sum2enteredNumbers(number1, number2)
{
var sum1and2;
sum1and2 = number1 + number2;
return sum1and2;
}
function exercise4Part1() {
// PART 1: YOUR CODE STARTS AFTER THIS LINE
var QUIT_CODE = "quit";
var output;
var number1;
var number2;
while (number1 !== QUIT_CODE && number2 !== QUIT_CODE)
{
number1 = prompt("Enter a number or \"quit\":");
number2 = prompt("Enter another number or \"quit\":");
if (number1 !== QUIT_CODE && number2 !== QUIT_CODE)
{
number1 = Number(number1);
number2 = Number(number2);
}
}
sum1and2 = sum2enteredNumbers(number1, number2);
output = document.getElementById('outputPart1');
output.innerHTML = "<br /> Entry 1: " + number1 + " Entry 2: " + number2 + " Sum: " + sum1and2;
}
Conceptually, you want to do this:
Get the user input,
if at any time the input is "quit", then stop. (the sentinel check)
perform the addition operation,
output,
repeat.
For step 1, you're most of the way there. Consider this function:
function getInput(msg) {
var value = prompt(msg);
if (value === QUIT_CODE) {
return false;
}
return value;
}
You can then call this function in the while condition, while still assigning the input to number1 or number2.
while ((number1 = getInput('Enter a number')) &&
(number2 = getInput('Enter another number'))) {
// convert and output
}
Why does this work?
&&, || , i.e. JavaScript's logical boolean operators short circuit, which means the condition will be false without evaluating the second operand if the first operand is false for &&, and the condition will be true without evaluating the second operand if the first operand is true.
One would normally think of 0 as falsey in JavaScript which would cause the while condition to fail and not work if the user entered 0. However in this case, the source of the input is a string, and the expression '0' is truthy.
I've just began Javascript in college. One task is to define and call a function to find the maximum number from 3 numbers entered by the user. I know there is a max() function but we were told to do it manually using if and else if.
I'm going wrong somewhere as you can see. It's just telling me the max is 0 everytime.
function maxNum(num1, num2, num3){
var max = 0;
if(num1 > num2){
if(num1 > num3){
num1 = max;
}
else{
num3 = max;
}
}
else{
if(num2 > num3){
num2 = max;
}
}
return max;
}
for(i=0;i<3;i++){
parseInt(prompt("Enter a number"));
}
document.write(maxNum());
Or you can use ES6 syntax, to compute largest of three numbers in easier way,
const largest = a => F = b => G = c => ((a > b && a > c) ? a : (b > a && b > c) ? b : c)
console.time()
console.log(largest(53)(30907)(23333))
console.timeEnd()
One problem you have is that you do not save the number the user inputs. You prompt them, parse it as an int and then nothing. You have to pass the 3 numbers into maxNum()
Here is a working example that uses proper left hand assignment and saves the number. Also it is a good idea to use >= instead of > because the user can enter 2 of the same number
function maxNum(num1, num2, num3){
var max = 0;
if((num1 >= num2) && (num1 >= num3)){
max = num1;
}
else if((num2 >= num1) && (num2 >= num3)){
max = num2;
}
else{
max = num3;
}
return max;
}
var arr = [];
for(i=0;i<3;i++){
arr[i] = parseInt(prompt("Enter a number"));
}
document.write(maxNum.apply(this, arr));
easiest way:
function maxNum(num1, num2, num3){
var tmp = 0;
if(num1 < num2 && num3 < num2) {
tmp = num2;
} else if(num3 < num1){
tmp = num1;
} else {
tmp = num3;
}
return tmp;
}
var arr = [];
for(var i = 0; i < 3; i++) {
arr[i] = prompt("Enter a number");
}
console.log(maxNum.apply(this, arr));
First in javascript and most modern programming language assignment like a = b copies the value of b into the variable a. It is not equivalent to b = a (which copies the value of a into the variable b). It's common to write a = 1, but a syntax error in most languages to write 1 = a. Thus, you don't want to write num1 = max, but instead write max = num1.
Second, your logic is incorrect as it won't treat the case maxNum(1,2,3) correctly. (Work through the logic when num1 < num2 and num2 < num3. The following code would work:
function maxNum(num1, num2, num3){
var max = 0;
if(num1 > num2){
if(num1 > num3){
max = num1;
}
else{
max = num3;
}
}
else{
if(num2 > num3){
max = num2;
} else {
max = num3;
}
}
return max;
}
Granted, I would probably write something like
function max3num(num1, num2, num3) {
var max_so_far = num1;
if (num2 > max_so_far) {
max_so_far = num2;
}
if (num3 > max_so_far) {
max_so_far = num3;
}
return max_so_far;
}
as the logic is very clear and it will be easy to extend to a max function with a larger number of elements to compare if necessary. (Adding in a for loop could make it variadic fairly easily). It is straightforward to see the logic works, because we start with the first element being the maximum so far (max_so_far), then consider if the second element is larger -- if so we assign that as max_so_far, and keep continuing until we have compared all the elements to the max_so_far. After we have considered each element once, we then return the max_so_far which will now be the maximum of all of them.
No real need for a function here, just compare them as the come in!
var max = 0;
for(var i=0;i<3;i++){
var val = parseInt(prompt("Enter a number"));
max = max > val ? max : val;
}
alert(max);
The updated direct answer is this :
function maxNum(num1, num2, num3){
return [num1, num2, num3].sort(function (a, b) { return b - a })[0];
}
If written like this, it can easily be modified to take any amount of numbers by passing it an array of said numbers.
var numArray = [num1, num2, num3, num4, ...];
function maxNum(numArray){
return numArray.sort(function (a, b) { return b - a })[0];
}
The details :
Take an array :
[5,42,16]
Now sort it.
[5,42,16].sort()
But this wont work because javascript .sort requires a function to be passed in. This function tells it how to sort the array.
This will sort it highest to lowest, e.g. a is less then b.
function (a, b) { return b - a }
This will sort it lowest to highest, e.g. b is less then a.
function (a, b) { return a - b }
So we add it in :
[5,42,16].sort(function (a, b) { return b - a })
But this returns the sorted array, not the maximum number.
So we pick the first element in the array :
[5,42,16].sort(function (a, b) { return b - a })[0]
Lastly, you can pull out the sort function. This is mostly for demo purposes though.
var maxSorter = function (a, b) { return b - a };
function maxNum(numArray){
return numArray.sort(maxSorter)[0];
}
//Raihan
// program to find the largest among three numbers
// take input from the user using Prompt
let num1 = parseFloat(prompt("Enter first number: "));
let num2 = parseFloat(prompt("Enter second number: "));
let num3 = parseFloat(prompt("Enter third number: "));
let largest = Math.max(num1, num2, num3);
// display the result
document.write("The largest number is " + largest);
**//another way**
const num1 = parseFloat(prompt("Enter first number: "));
const num2 = parseFloat(prompt("Enter second number: "));
const num3 = parseFloat(prompt("Enter third number: "));
// check the condition
if(num1 >= num2 && num1 >= num3) {
document.write("Largest Number : " + num1)
}
else if (num2 >= num1 && num2 >= num3) {
document.write("Largest Number : " + num2)
}
else {
document.write("Largest Number : " + num3)
}