i have a set of radio buttons, each holding a number as their value (odd/even) and upon clicking a button an output is shown in a label and have managed to do that much, but now i am not sure how to reference the value of the button to output in the label this message:'mary the number [number] is [odd/even]'
this image shows this code:
let num1 = 176
let num2 = 345
let num3 = 1037
let num4 = 3421
let num5 = 2289
let num6 = 3044
rdoOddEven.onclick=function(){
if Number($"input[name=rdoOddEven]:checked").prop("value")%2==0
lblOddEven.className=''
lblOddEven.style.color='black'
lblOddEven.value = `Mary, the number ${$("input[name=rdoOddEven]:checked").prop("value")} is even`
else if Number($"input[name=rdoOddEven]:checked").prop("value")%2==1
lblOddEven.className=''
lblOddEven.style.color='black'
lblOddEven.value = `Mary, the number ${$("input[name=rdoOddEven]:checked").prop("value")} is odd`
}
First of all, check your syntax. JavaScript follows the core syntax of the C language. The if construct requires that you enclose the whole expression to be evaluated between (). And when you need to conditionally execute several lines, you must enclose them between {}.
You may compare this code with yours.
let num1 = 176
let num2 = 345
let num3 = 1037
let num4 = 3421
let num5 = 2289
let num6 = 3044
rdoOddEven.onclick=function() {
if (Number($"input[name=rdoOddEven]:checked").prop("value")%2==0) {
lblOddEven.className=''
lblOddEven.style.color='black'
lblOddEven.value = `Mary, the number ${$("input[name=rdoOddEven]:checked").prop("value")} is even`
}
else if (Number($"input[name=rdoOddEven]:checked").prop("value")%2==1) {
lblOddEven.className=''
lblOddEven.style.color='black'
lblOddEven.value = `Mary, the number ${$("input[name=rdoOddEven]:checked").prop("value")} is odd`
}
}
Related
I am trying to exclude 0 in my average code. The code is supposed to ask the user to write 4 numbers and then output an average between them 4.
The code works fine, but now I want to exclude 0s from the code, and it worked but only if you digit 0 one time. For example: I want to exclude two 0s but I have no idea how to do it. My idea was to delete the num that has 0 in it so the operation calculates the 0\> numbers only. There is my code:
var num1 = parseInt(prompt("first number: "),10);
var num2 = parseInt(prompt("second number: "),10);
var num3 = parseInt(prompt("third number: "),10);
var num4 = parseInt(prompt("fourth number: "),10);
if (num1==0){
document.getElementById("output").textContent = ((num2 + num3+ num4) / 3);
}
if (num2==0){
document.getElementById("output").textContent = ((num1 + num3+ num4) / 3);
}
if (num3==0){
document.getElementById("output").textContent = ((num1 + num2+ num4) / 3);
}
if (num4==0){
document.getElementById("output").textContent = ((num1 + num2+ num3) / 3);
}
else {
document.getElementById("output").textContent = ((num1 + num2 + num3+ num4) / 4);
}
Think about your current line of thought.
You wrote some code that averages between 3 numbers if one of the 4 numbers is zero. Now you realize it doesn't work when 2 of the 4 numbers are zeroes. How many more if-elses would you need to write to accommodate that? Then imagine if 3 of them were zeroes.
This problem is pretty simple because you only take 4 inputs. Now imagine if you took 100 inputs and are trying to get averages of all the non-zero integers from there.
A much more scalable solution would be to have it be such that no matter how many inputs you take, the code will only look at and average the non-zero integers. Something like this:
let num1 = 3; //imagine it were equivalent to var num1 = parseInt(prompt("first number: "),10);
let num2 = 4; //imagine it were equivalent to var num2 = parseInt(prompt("second number: "),10);
let num3 = 0; //imagine it were equivalent to var num3 = parseInt(prompt("third number: "),10);
let num4 = 0; //imagine it were equivalent to var num4 = parseInt(prompt("fourth number: "),10);
const numbers = [num1, num2, num3, num4]
function avgNonZeroValues(nums){
const nonZeros = nums.filter(number => number !== 0);
const avgOfNonZeros = nonZeros.reduce(
(accumulator, currentValue) => accumulator + currentValue,
0
)/nonZeros.length;
return avgOfNonZeros;
}
console.log(avgNonZeroValues(numbers));
You need to know two functions:
reduce()
Reduce is a very handy method to go through a list/array and do something with it. It takes in a initial value(0 for us), and we also tell it what to do with every element. Here, we are saying "keep on adding the elements. Here, we are using it to get the sum of all the numbers in the array.
filter()
Filter is pretty self-explanatory. You give this function an array and a condition, and it will filter out the elements that do not satisfy the condition, and will give you a new array of all the elements that do satisfy the condition. Here, we are using it to filter all the zeros out of the array.
You give this function avgNonZeroValues an array of any length containing numbers, it will remove all the 0s and average the rest of them.
Refactoring this to use arrays allows easy use of array functions to filter and transform the numbers.
const prompts = ["first", "second", "third", "fourth"];
const values = prompts
.map(p => parseInt(prompt(`${p} number: `),10))
.filter(v => v !== 0);
const total = values.reduce((acc, val) => acc + val, 0);
const avg = total/values.length;
console.log(total, avg);
I have a number which looks number this:
800.60000305176541
This number changes all the time.
So I'm doing this:
var mynumber = 800.60000305176541
var changenumber = mynumber.toFixed(3);
This is displaying 800.600 ... I need it to display the last 3 like:
800.541
How can I do this?
You can convert to string and do your manipulations.
Please note we are loosing the right most digit due to limits of javascript.
var num = 800.60000305176541;
var str = "" + num
var arr = str.split(".");
var result = arr[0]
if (arr[1]) {
result += "." + arr[1].slice(-3)
}
console.log(num)
console.log(result)
You could also try to solve it mathematically.
800.60000305176541
800.60000305176000 -
------------------
800.00000000000541
.00000000000541
10^10. X
------------------
0,541 + 800 = 800.541
This question already has answers here:
Why is parseInt() not working? [duplicate]
(4 answers)
Closed 3 years ago.
Here's my code:
function add() {
var num1 = prompt("Enter 1st number")
var num2 = prompt("Enter 2nd number")
parseInt(num1);
parseInt(num2);
var result = num1 + num2;
alert(result);
}
add();
I'm trying to build a simple addition calculator. parseInt wasn't working and an answer here said to declare the variable like var num1 = parseInt(num1);. However since I'm only getting "num1" through user input (var num1 = prompt..."), not sure how to store it as integer, or parseInt, in the same line. Any advice? Thanks.
All you have here are standalone, unused expressions:
parseInt(num1);
parseInt(num2);
Those evaluate to numbers, but you don't use them, so they're useless. Either assign them to variables, eg
const actualNum1 = parseInt(num1);
const actualNum2 = parseInt(num2);
and then use those variables, or just wrap the prompt in parseInt:
var num1 = parseInt(prompt("Enter 1st number"))
var num2 = parseInt(prompt("Enter 2nd number"))
Unless you're intending to only accept integers, consider using Number instead:
var num1 = Number(prompt("Enter 1st number"))
var num2 = Number(prompt("Enter 2nd number"))
Im trying to accept 2 inputs from a user then compare the 2 to find the smallest number.
Finally print to the console. I feel Im going in the wrong direction.
Any advice?
Below is my code
//prompt variable for user input
let num1 = prompt("Enter 1st number ", "i.e. 7 ");
let num2 = prompt("Enter 2nd number ", "i.e. 4 ");
// for loop returning lowest input
for (let i = 1; i < num1.length; i++){
if (num1[i] <= num2){
num2 = num1[i];
}
}
console.log(num2);
If there's only 2 inputs and you're trying to console.log the smallest number then you can just use an if statement. No need to iterate through num1.
let num1 = 5;
let num2 = 10;
if(num1 > num2){
console.log(num2);
}else if (num2 > num1){
console.log(num1);
}else{
console.log(num1 + ' and '+num2+' are equal');
}
I'm currently struggling with getting the below calcRatio function calculate properly. This is probably basic maths!
The below function works as expected:
function calcRatio(){
var r = frontRing.value/backCog.value;
return r;
}
e.g. frontRing = 52, backCog = 11 r=4.7272....
The below gives me the wrong result:
function calcRatio(){
var r = frontRing.value/(backCog.value + 5);
return r;
}
e.g. frontRing = 52, backCog = 11 r=0.4521.
I ultimately want the 5 to be swapped with an argument.
I am also unable to set the frontRing and backCog variable as .value's without doing it within the function. Could this be causing the issue?
Codepen link
When you expect the extracted value to be a string and have additional computations, it is preferred you use either
parseInt( value , 10) - for integers
parseFloat( value ) - for decimals
In the use case var r = frontRing.value/(backCog.value + 5);
backCog.value is a string since it it a value of input element. When you use + to add a number, it performs a concatenation instead of addition.
var backCogValue = backCog.value; // "11";
"11" + 5 --> 115 and not 16 as you expected.
So the right way to write this piece of code is to use either of the above methods before you want to add a number.
var frontRingValue = parseFloat(frontRing.value);
var backCogValue = parseFloat(backCog.value);
var r = (frontRingValue/ (backCogValue + 5)).toFixed(4);
toFixed is use to format into the number of decimal points that you are expecting.
If 5 is the argument that is passed to the function, then your code will look like
function calcRatio(param) {
var frontRingValue = parseFloat(frontRing.value);
var backCogValue = parseFloat(backCog.value);
var paramValue = parseFloat(paramValue);
var r = (frontRingValue/ (backCogValue + paramValue)).toFixed(4);
}