Why isn't this HTML/Javascript code working? [duplicate] - javascript

This question already has answers here:
JavaScript: How to reverse a number?
(19 answers)
Closed 3 years ago.
I want to create a program which helps me find the reverse of a number. So, if I enter the number 135, it gives back 531 to me. I created the code, with the help of various online sources that confirm that my method is correct. However, I cannot seem to create a solution. I tried using a while loop in a similar fashion, as well. The output always comes out as Infinity. Is there a problem with my technique or the code.
<input type="button" value="Find the Reverse of a Number" onclick="inv()">
<script>
function inv() {
var n = prompt("Enter a number: ");
var rev = 0;
for (; input !== 0;) {
var lastDigit = input % 10
rev = rev * 10;
rev = rev + lastDigit;
input = input / 10;
}
}
</script>

check it .
var a = prompt("Enter a value");
var b, sum = 0;
var z = a;
while(a > 0)
{
b = a % 10;
sum = sum * 10 + b;
a = parseInt(a / 10);
}
alert(sum);

Try this:
function inv(){
var n = prompt("Enter a number: ").toString();
n = [...n].reverse().join("");
alert(`Reversed ${n}`)
}
<input type="button" value="Find the Reverse of a Number" onclick="inv()">

Related

Why doesn't my JavaScript program to find odd numbers work? [duplicate]

This question already has answers here:
Javascript string/integer comparisons
(9 answers)
Sum of two numbers with prompt
(10 answers)
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
Closed 1 year ago.
I made a simple js code to input start value and end value form prompt and then find all the odd numbers, unfortunately it's not working properly. when i input 1 and 10 it'll work, but when i input 5 for sValue(start value) the program won't work. any idea?
var odd = [];
var sValue = prompt("start");
var eValue = prompt("end");
for (var i = sValue; i <= eValue; i++) {
if (i % 2 != 0) {
odd.push(i);
}
}
alert(odd);
Because the value of prompt is a string. You need to convert it to a number with parseInt(v, 10).
var odd = [];
var sValue = parseInt(prompt("start"), 10);
var eValue = parseInt(prompt("end"), 10);
for (var i = sValue; i <= eValue; i++) {
if (i % 2 != 0) {
odd.push(i);
}
}
alert(odd);

JavaScript sum of numbers in an array producing string instead of numbers [duplicate]

This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 2 years ago.
The code below is outputting a string of numbers instead of the sum of the numbers in the array. For example, if n is set to 3 and the numbers 1 2 3 are added to the array the output is 0123 when I need it to be 6. I can only use while loops and not for loops for this which is why the code looks slightly odd. Can someone please explain to me why the output is a string and not the sum of the numbers?
var n = -1;
var n2 = 0;
var numbers = [];
while (n < 0) {
n = prompt("Please enter a positive interger");
}
while (n > 0) {
n2 = prompt("Please enter a interger");
numbers.push(n2);
n = n - 1
}
var sum = numbers.reduce(function(a, b){
return a + b;
}, 0);
alert(sum);
All you need to change is where you push the numbers to the array from
numbers.push(n2);
to
numbers.push(parseInt(n2, 10));
because the prompt believes always that the user inserts a string.
var n = -1;
var n2 = 0;
var numbers = [];
while (n < 0) {
n = prompt("Please enter a positive interger");
}
while (n > 0) {
n2 = prompt("Please enter a interger");
numbers.push(parseInt(n2, 10));
n = n - 1
}
var sum = numbers.reduce(function(a, b){
return a + b;
}, 0);
alert(sum);
Prompt always return a string. You have to parse it:
strN = prompt("Please enter a positive interger");
n = parseInt(strN);

Calculate the sum of all even numbers between n and m [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I need to calculate numbers between n and m, but something goes wrong and I don't know what..
function even(){
var n = document.getElementById("n").value;
var m = document.getElementById("m").value;
var s = 0 ;
if(n<m){
i = n;
while(i<=n){
n*(n+2)/4;
i++;
alert(n.value)
}
}else if(n>m);{
i=m;
S=n*(n+2)/4;
i++
alert(m.value)
}
}
<input type="text" id="n" > </br><br>
<input type="text" id="m" > </br><br>
<button onclick="even()">Click me !</button>
Unless you are specifically told to use a loop you should use the formula for sum of arithmetic progression.
function even() {
let n1 = Number(document.getElementById("n").value);
let n2 = Number(document.getElementById("m").value);
if (n1 > n2) [n1,n2] = [n2,n1];
n1 = 2*Math.ceil(n1/2);
n2 = 2*Math.floor(n2/2);
if (n1 > n2) return 0;
return (n1 + n2) * ((n2 - n1) / 2 + 1) / 2;
}
<input type="text" id="n" > <br><br>
<input type="text" id="m" > <br><br>
<button onclick="alert(even())">Click me !</button>
Even if you use a loop you should consider making number even first and then increment loop variable by 2 every time instead of checking parity on each iteration.
You were trying to calculate the sum, however, in your while loop, you were not adding it to the sum and trying to alert n.value or m.value which will be undefined here as there is no value property.
You can define a logic for the same (AP) rather than looping
function even(){
// convert the values to numbers otherwise it will be strings
var n = parseInt(document.getElementById("n").value);
var m = parseInt(document.getElementById("m").value);
if (n > m) [n, m] = [m, n]; // store smaller number in n
n = (n%2 === 0) ? n: n+1; // find the first even number
m = (m%2 === 0) ? m: m-1; // find the last even number
var s = 0; // initialize sum to 0
if(m >= n) {
var numbers = (m-n)/2 + 1; // number of even numbers in the range
/* Understanding the formula. It is a basic airthmetic series of n
* numbers, with first number being a, last number being l
* which is equal to (a + (n-1)d) where difference
* being d. The sum will be n/2(a+l) => n/2(a + a + (n-1)d)
* => n/2(2a + (n-1)d). With our d being 2, equation becomes
* n/2(2a +(n-1)2) => n(a + n -1). */
s = numbers*(n + numbers-1);
}
alert(s);
}
<input type="text" id="n" > </br><br>
<input type="text" id="m" > </br><br>
<button onclick="even()">Click me !</button>
Or you can update your code to following
function even(){
// convert the values to numbers otherwise it will be strings
var n = parseInt(document.getElementById("n").value);
var m = parseInt(document.getElementById("m").value);
var s = 0 ;
var i;
// Iterate over the numbers and check if it is divisible by 2 if yes then add it to the sum and finally alert the sum
if(n<m){
i = n;
while(i<=m){
if(i%2 === 0) s += i;
i++;
}
alert(s);
}else if(n>m) {
i=m;
while(i<=n){
if(i%2 === 0) s += i;
i++;
}
alert(s);
}
}
<input type="text" id="n" > </br><br>
<input type="text" id="m" > </br><br>
<button onclick="even()">Click me !</button>
To perform calculations only for even numbers, you need to find the remainder of the division. The remainder of the division must be zero
let a = 2;
let b = 10;
for(let i = a; i <= b; i++){
if (i%2 === 0){
// do something here even numbers
}
}
Try this:
if (n < m) {
for (let i = n; i <= m; i++) {
if (i%2 === 0)
s += i;
}
} else {
for (let i = m; i <= n; i++) {
if (i%2 === 0)
s += i;
}
}
The line if (s%2 === 0) is key to this because it will only add the numbers in the range which have a 0 remainder when divided by 2 (are even).
I've also converted the while loops you had into for loops because they are cleaner and easier to read.
You could also attempt to use ternary operators to quickly set-up lower and upper variables if you want to eliminate the need for the outer if-else statements.
I have taken the numbers as 10 and 3 and I am not considering both the numbers in loop because you have asked for sum of even numbers between these two.I have taken sum as 0.I have found the highest and lowest number using Ternary operator.using for loop i have found the Even integers and added them.
var x=10;
var y=3;
var higher=x>y?x:y;
var lower=x>y?y:x;
var sum=0;
for(var i=lower+1;i<higher;i++){
if(i%2==0){
sum+=i;
}
}
console.log("sum is"+sum)

Insert a Comma in the thousandths place in outputted number [duplicate]

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 6 years ago.
I have created a function that takes a number in Imperial units entered into a div and converts that value to metric units in another div. Being relatively new to js, I am now realizing that a thousandths place comma separator does not come standard. I've tried to apply many of the solutions (many of them reg ex's) that I've found but none suit my needs or have worked. Simply put, I am just looking to have both divs outputted numbers have commas separating the thousandths place. Ultimately, these numbers are elevation values expressed in Feet and Meters. Any insight would be greatly appreciated... thanks!
Here is my code:
<body>
<div id="feet" onload="calculateMeter()">2120</div>
<div id="meter"></div>
<script>
var feet = document.getElementById('feet');
var meter = document.getElementById('meter');
function calculateMeter() {
if (feet.innerHTML > 0) {
meter.innerHTML = (feet.innerHTML * 0.3048).toFixed(1);
feet.toString();
feet = feet.innerHTML.replace(/(\d)(\d{3})\,/, "$1,$2.");
}
}
calculateMeter();
</script>
</body>
Here is a simple RegEx solution
function calculateMeter() {
if (feet.innerHTML > 0) {
var m = (feet.innerHTML * 0.3048).toFixed(2);
meter.innerHTML = m.replace(/\B(?=(\d\d\d)+\b)/g, ",");
}
}
It seems your problem is actually just setting the content the DOM element. Using the solution in How to print a number with commas as thousands separators in JavaScript for formatting numbers, all you need is:
function calculateMeter() {
if (feet.innerHTML > 0) {
meter.innerHTML = numberWithCommas*(feet.innerHTML * 0.3048).toFixed(1));
feet.innerHTML = numberWithCommas(feet.innerHTML);
}
}
My function:
function formatNumberWithCommasDec(d) {
d += "";
var c = d.split(".");
var f = c[1];
var a = c.length > 1 ? c[0] + '.' : '.', flag = false;
var g = f.split('').reverse(), y = 1, s = '';
for (var i = g.length - 1; i >= 0; i--) {
flag = false;
var e = g[i];
var h = (y === 3) ? s = s + e + ',' : s = s + e;
console.log(e);
if(y === 3){
y = 1;
flag = true;
} else {
y = y + 1;
}
}
if(flag){
s = s.substring(0, s.length - 1);
} else {
s = s;
}
return a + s;
}
Fiddle: https://jsfiddle.net/6f0tL0ec/1/
Update: found some problems, but everythings good now

how to divide a number a in a series of all whole numbers?

Hi sorry for asking this if this is a stupid question.
I would like to ask how to securely divide a number in Javascript that it will always
output the result in a way that it will output pure whole numbers.
example:
10 / 2 ---> 5, 5 ( it would be 2 fives so it is whole number )
BUT
10 / 3 ---> 3, 3, 4 ( it would have two 3 and one 4 so that it would still result to 10 )
10/3 will give you 3.333333..., never four... if you want to check is a number will give you "whole numbers" as you say, use modulo (%).
Modulo finds the remainder of division of one number by another.
For example
10%5 = 0 because 10 divided by 5 is a "whole number"
10%3 = 1 because the closest 10/3 is 3... 3x3=9... 10-9=1
So in your code, if you want to know if a number divided by another number is whole, you need to do
if (number1%number2 == 0) { ... }
Read more about it here
EDIT :
I read your question again and I think this fiddle is what you want
var number1 = 10,
number2 = 3;
if (number1 / number2 == 0) {
alert('the numbers are whole');
} else {
var remainder = number1%number2;
var wholes = Math.floor(number1 / number2);
var output = '';
for (var i = 0; i < (wholes - 1); i++) {
output+= number2 + ', ';
}
output += (number2 + remainder);
alert(output);
}
Whatever your result is,just pass it through the parseInt function,For Eg:-
Suppose your answer is 4.3,
The whole number close to it will can be accounted using,
parseInt(4.3)
Which equals 4.
Another posibility: make the number a string and walk all the elements
var a = 11 / 4;
//turn it into a string and remove all non-numeric chars
a = a.toString().replace(/\D/g, '');
//split the string in seperate characters
a = a.split("");
var num = new Array();
//convert back to numbers
for (var i = 0; i < a.length; i++) {
num.push(parseFloat(a[i]));
}
alert(num);
On a sidenote, you'll have to do some kind of rounding, to prevent eternally repeating numbers, like 10/3.
Here is a fiddle
Look at this very simple example:
var x = 10;
var y = 3;
var result = x/y;
var rest = x%y;
for (var i=0; i<y; i++) {
var output;
if(i==y-1){
output = parseInt(result + rest);
}
else{
output = parseInt(result);
}
alert(output);
}
http://jsfiddle.net/guinatal/469Vv/4/

Categories