I'm trying to recreate a simple project I have in my fundamentals class to javascript (from C++) but sum doesn't add every time the for loop runs. All other parts are ok but sum just lists the numbers in the order I put them in. Any help is appreciated
var num = prompt("Please enter an integer");
var lrg = num;
var sml = num;
var avg = num;
var sum = num;
var cnt = 10;
function runMath () {
for (i = 1; i < 10; i++) {
var num = prompt("Please enter an integer");
if (num > lrg) {
lrg = num;
} else {
lrg = lrg;
}
if (num < sml) {
sml = num;
} else {
sml = sml;
}
sum += num;
}
}
runMath();
avg = sum/cnt;
The problem is that prompt() returns a String, whereas you are expecting a number. You can turn this into a number in a few different ways:
parseInt("33") will return 33, instead of "33"
Likewise, shorthand would look like:
+prompt("33") will return 33, instead of "33"
All input is from the prompt() command is a string. You can convert it to an integer using parseInt(), but the user can enter something other than a number, so you will need to check if it isNaN() (is Not a Number), and deal with it differently if it is.
var num = prompt("Please enter an integer");
num = parseInt(num, 10)
if (isNaN(num)) {
alert ("That's not a number")
num = 0 // or do something else
}
Caution: typeof NaN will return "number", so you can't rely on that as a test (see NaN)
An explanation of the + in +prompt: Unary plus (+)
Related
I run the code multiple times but couldn't find the problem!!
A Narcissistic Number is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).
Your code must return true or false (not 'true' and 'false') depending upon whether the given number is a Narcissistic number in base 10.
function narcissistic(value) {
let strDigits = value.toString();
let power = strDigits.length;
let arrayDigits = strDigits.split('');
let sum, poweredValue = 0;
for (let i = 0; i < power; i++){
poweredValue = Number(arrayDigits[i])**power;
sum += poweredValue;
}
if (sum === value){
return true;
}else {
return false;
}
};
You have to assign the initial value for sum as 0. By default, it's set to undefined. And adding something to undefined gives NaN, and any comparison with NaN is always false.
function narcissistic(value) {
let strDigits = value.toString();
let power = strDigits.length;
let arrayDigits = strDigits.split("");
let sum = 0,
poweredValue = 0;
for (let i = 0; i < power; i++) {
poweredValue = Number(arrayDigits[i]) ** power;
sum += poweredValue;
}
if (sum === value) {
return true;
} else {
return false;
}
}
You assumed that the statement of the form:
let x, y =0;
initialize x and y both as 0. But x is still undefined.
And type undefined + type number will evaluate to NaN (not a number).
And no number is equal to NaN
Just initialize properly:
function narcissistic(value) {
let strDigits = value.toString();
let power = strDigits.length;
let arrayDigits = strDigits.split('');
let sum =0, poweredValue = 0;
for (let i = 0; i < power; i++){
poweredValue = Number(arrayDigits[i])**power;
sum += poweredValue;
}
if (sum === value){
return true;
}else {
return false;
}
};
console.log(narcissistic(153));
Something like that?
const n = 153
function action(n) {
let sum = 0;
n.toString().split('').forEach(i => {
sum += parseInt(i)**n.toString().length;
})
return sum == n
}
console.log(action(n))
I need to ask user to input a 3 digit number and then swap the first and last numbers using a for loop. This is what I have so far, but I'm stuck. Using a for loop seems illogical, but that is what I have to do:
num = prompt("Please input a number with 3 digits.");
let firstDigit = num[0];
let secondDigit = num[1];
let lastDigit = num[2];
for (firstDigit < 10; secondDigit < 10; lastDigit < 10); {
console.log(lastDigit + secondDigit + firstDigit);
}
Please help!
Thanks
is it help for you?
// let num = prompt("Please input a number with 3 digits.");
// if (num.length > 3) alert("3 digits please");
// else {
// let answer = "";
// for (var i = 2; i >= 0; i--) {
// answer = answer + num[i];
// }
// console.log(answer);
//}
let num = prompt("Please input a number");
let temp = "";
let answer = "";
for(let i = 0 ; i < num.length; i++) {
if (i === 0) temp = num[i]; // save first number to temp
else if (i === num.length - 1) {
// When the last number is encountered, the last number is put at the beginning, and the first number stored in temp is put at the end.
answer = answer + temp;
answer = num[i] + answer;
}
else answer = answer + num[i];
}
console.log(answer);
I'm having some trouble trying to do a digital root exercise on Javascript.
Here's my code:
function digital_root(n) {
var sNumero = n.toString();
var sum = 0;
for(i = 0 ; i < sNumero.length; i++){
sum += parseInt(sNumero[i]);
}
if(sum > 9){
digital_root(sum);
}
return sum;
}
When I try to input 456 to 'n', the function gives 15 as the return. The expected is 6. I don't know why this is happening.
To help you guys understand my problem, here's the exercise:
"A digital root is the recursive sum of all the digits in a number. Given n,
take the sum of the digits of n. If that value has more than one digit,
continue reducing in this way until a single-digit number is produced. This is
only applicable to the natural numbers."
You forgot a return:
if(sum > 9){
return digital_root(sum); // <-- here
}
You can add a return statement here on
function digital_root(n) {
var sNumero = n.toString();
var sum = 0;
for (i = 0; i < sNumero.length; i++) {
sum += parseInt(sNumero[i]);
}
if (sum > 9) {
return digital_root(sum); // missing return here
}
return sum;
}
console.log(digital_root(456))
OR add a new variable to capture the final result before returning.
function digital_root(n) {
var sNumero = n.toString();
var sum = 0;
var final_result; // introduce new variable to hold recursive sum
for (i = 0; i < sNumero.length; i++) {
sum += parseInt(sNumero[i]);
}
final_result = sum; // assign sum to final_result variable
if (sum > 9) {
final_result = digital_root(sum);
}
return final_result; // return final_result
}
console.log(digital_root(456))
Question:
Write a function called sumDigits.
Given a number, sumDigits returns the sum of all its digits.
var output = sumDigits(1148);
console.log(output); // --> 14
If the number is negative, the first digit should count as negative.
var output = sumDigits(-316);
console.log(output); // --> 4
This is what I currently have coded and it works for positive values but I can't wrap my head around how to tackle the problem when given a negative value. When -316 is put into the function, NaN is returned and I understand that when I toString().split('') the number, this is what is returned: ['-', '3', '1', '6']. How do I deal with combining index 0 and 1?
function sumDigits(num) {
var total = 0;
var newString = num.toString().split('');
for (var i = 0; i < newString.length; i ++) {
var converted = parseInt(newString[i]);
total += converted;
}
return total;
}
sumDigits(1148);
Any hints on what methods I should be using? and is there a smarter way to even look at this?
This should do it:
function sumDigits(num) {
var total = 0;
var newString = num.toString().split('');
for (var i = 0; i < newString.length; i ++) {
if(newString[i]==='-') { //check to see if the first char is -
i++; //if it is, lets move to the negative number
var converted = parseInt(newString[i]); // parse negative number
total -= converted; // subtract value from total
continue; // move to the next item in the loop
}
var converted = parseInt(newString[i]);
total += converted;
}
return total;
}
console.log(sumDigits(-316));
You could always use String#replace with a function as a parameter:
function sumDigits (n) {
var total = 0
n.toFixed().replace(/-?\d/g, function (d) {
total += +d
})
return total
}
console.log(sumDigits(-1148)) //=> 14
One way to do this, is to do a split that will keep the minus and the first digit together, not split.
You can do that with a regular expression, and use match instead of split:
var newString = num.toString().match(/-?\d/g);
function sumDigits(num) {
var total = 0;
var newString = num.toString().match(/-?\d/g);
for (var i = 0; i < newString.length; i++) {
var converted = parseInt(newString[i]);
total += converted;
}
return total;
}
var result = sumDigits(-316);
console.log(result);
In a bit shorter version, you could use map and reduce, like this:
function sumDigits(num) {
return String(num).match(/-?\d/g).map(Number).reduce( (a, b) => a+b );
}
console.log(sumDigits(-316));
Is there a smarter way to even look at this?
You can avoid the conversion from number to string and back by using the modulo operator to extract the last digit. Repeat this step until you got all digits:
function sumDigits(num) {
let total = 0, digit = 0;
while (num != 0) {
total += digit = num % 10;
num = (num - digit) * 0.1;
}
return total < 0 ? digit + digit - total : total;
}
console.log(sumDigits(-316)); // 4
console.log(sumDigits(1148)); // 14
console.log(sumDigits(Number.MAX_SAFE_INTEGER)); // 76
function sumDigits(num) {
let string = num.toString();
let zero = 0;
let total = 0;
for (var i = 0; i < string.length; i++) {
if (Math.sign(num) === 1) {
total = zero += Number(string[i]);
} else {
for (var i = 2; i < string.length; i++) {
total = (zero += Number(string[i])) - Number(string[1]);
}
}
}
return total;
}
I'm trying to write a function that determines whether a value is a prime number and then displays a message to provide the outcome. Unfortunately, it doesn't work - no error messages displayed, and I can't see a logical reason why. ( For info, it calls a function numbers() which I have tested independently and it works - it provides a single positive integer). I'm not very experienced in javascript, but have developed the below from learning online. Any pointers in the right direction would be very much appreciated.
function validate() {
var message = "This number is ";
var number;
var value = numbers();
var indicator = true;
for (int i=2; i <= value/2; i++) {
number = value % i;
if (number==0) {
indicator = false;
//or indicator = number % 2 != 0;
break;
}
}
if (indicator) {
message += "a prime number.";
}
else {
message += "not a prime number.";
}
document.getElementById('text').innerHTML = message;
}
Only even number that is prime is 2, so discard all the others that is divisible by 2
Minimize the iteration by considering odds only
Minimize a bit more by iterating to root of given number
So what you can do is write a method like the following:
function isPrime(number) {
if (number === 2) return true;
if (number % 2 === 0) return false;
var flag = true;
var i, length = Math.ceil(Math.sqrt(number));
for (i = 3; i <= length; i += 2) {
if (number % i === 0) {
flag = false;
break;
}
}
return flag;
}
replace int to var in for loop
for (var i=2; i <= value/2; i++) {