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 2 years ago.
Improve this question
i tried a few ways to get a random number from 1 to 10 and all return undefined or NaN why ?
here is what i tried
var num = Math.floor(Math.random * 10)
function getNum() {
return Math.floor(Math.random * 10);
}
var num2 = getNum();
console.log('num = ' + num + 'num2 = ' + num2);
both dosn't give a number when logged
You need to actually invoke Math.random if you intend for it to generate the random number (ie Math.random())
var num = Math.floor(Math.random() * 10)
function getNum() {
return Math.floor(Math.random() * 10);
}
var num2 = getNum();
console.log('num = ' + num + 'num2 = ' + num2);
Math.random is a method, not a property, so you need to call it as Math.random(). You are also missing a semicolon after your first line.
As stated by #kloddant Math.random is method so you forgot the parentheses ().
So here's the snippet of how you can implement it
var num = Math.floor(Math.random() * Math.floor(10))
function getNum() {
return Math.floor(Math.random() * Math.floor(10));
}
var num2 = getNum();
console.log('num = ' + num + 'num2 = ' + num2);
Related
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 1 year ago.
Improve this question
This is my code, a simple sequel of function were I generate two number, one for the user, one for the PC and who scores the highest number win the game.
Firefox has come out with Uncaught SyntaxError: unexpected token: string literal error, I checked my code and everything seems ok to me, I can't figure out what's wrong and generates that error
// Generate a random number between 1 and 6 both for user and PC.
// Who does the highest score win.
//I create the random number for user and PC
var userNumber = getRandomNumber(1, 6);
var pcNumber = getRandomNumber(1, 6);
console.log(userNumber);
console.log(pcNumber);
//With highestScore function the winner comes out
var whoWon = highestScore(userNumber, pcNumber);
console.log(whoWon);
//I use this function to obtain the random number
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
//Function highestScore tell who's won the game
//matchMessage tells how the winner or the eventual tie has come
//The return is obviously matchMessage
function highestScore (num1, num2) {
var matchMessage = 'Your number is ' + num1 ', PC number is ' + num2 ', tie!!';
if (num1 > num2) {
matchMessage = 'Your number is ' + num1 ', PC number is ' + num2 ', congrats you've won';
} else if (num1 < num2) {
matchMessage = 'Your number is ' + num1 ', PC number is ' + num2 ', you lost...';
}
return matchMessage;
}
You are missing a plus + sign while adding the strings with variables.
What you are doing:
'Your number is ' + num1 ', PC number is '
What it should be:
'Your number is ' + num1 + ', PC number is '
When you are using the same type of quote in a string then you have two ways to correct it:
Use different strings, like:
", congrats you've won"
Or you can escape that string using \, Like
', congrats you\'ve won'
Try this:
// Generate a random number between 1 and 6 both for user and PC.
// Who does the highest score win.
//I create the random number for user and PC
var userNumber = getRandomNumber(1, 6);
var pcNumber = getRandomNumber(1, 6);
console.log(userNumber);
console.log(pcNumber);
//With highestScore function the winner comes out
var whoWon = highestScore(userNumber, pcNumber);
console.log(whoWon);
//I use this function to obtain the random number
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
//Function highestScore tell who's won the game
//matchMessage tells how the winner or the eventual tie has come
//The return is obviously matchMessage
function highestScore(num1, num2) {
var matchMessage = 'Your number is ' + num1 + ', PC number is ' + num2 + ', tie!!';
if (num1 > num2) {
matchMessage = 'Your number is ' + num1 + ', PC number is ' + num2 + ', congrats you\'ve won';
} else if (num1 < num2) {
matchMessage = 'Your number is ' + num1 + ', PC number is ' + num2 + ', you lost...';
}
return matchMessage;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I was looking to convert from Number to Roman (X, IV etc).
Someone proposed this solution, I'm going through the solution but I wasn't able to understand even though I debugged it.
Can someone explain what's going on? I'm just trying to learn some JS.
function convertToRoman(num) {
var roman = {"M" :1000, "CM":900, "D":500, "CD":400, "C":100, "XC":90, "L":50, "XL":40, "X":10, "IX":9, "V":5, "IV":4, "I":1};
str = "";
for (var i in roman ) {
var q = Math.floor(num / roman[i]); //Why?
num -= q * roman[i]; //Why?
str += i.repeat(q); //Why?
}
return str;
}
Description
Code described in comments below.
// this is a function declaration
// with a parameter called num
function convertToRoman(num) {
// this is an object, being used as a lookup
var roman = {"M" :1000, "CM":900, "D":500, "CD":400, "C":100, "XC":90, "L":50, "XL":40, "X":10, "IX":9, "V":5, "IV":4, "I":1};
console.log('num = ' + num);
// this is a variable of type string
str = "";
// for loop to go over each item in roman
for (var i in roman ) {
console.log('i = ' + i);
// calculates the Math Floor of the number passed in divided by the roman value
// this will do the number passed divided by 1000 first
// Example: convertToRoman(1201)
// Math.floor(1201 / 1000) = 1
var q = Math.floor(num / roman[i]); //Why?
console.log('q = ' + q);
// remove the value of q multiplied by roman[i]
// Example: convertToRoman(1201)
// q = 1
// num = num - 1 * 1000;
// this makes it so that num is less the roman symbol we just found
num -= q * roman[i]; //Why?
console.log('num = ' + num);
// this is to make the roman number string
// Example: num = 1201
// i = 1000
// q = 1
// str = str + "M";
// or
// num = 3102
// i = 1000
// q = 3
// str = str + "M" [repeated 3 times]
// str = 'MMM' at the end of this
str += i.repeat(q); //Why?
console.log('str = ' + str);
}
// return the string
return str;
}
console.log(convertToRoman(1201));
The var roman is an associative array with key being a string and value the decimal system value.
It's ordered descending in value.
The loop iterates the array calculating the max times each value at index is contained within the given number, and subtracting it from the number so that the new iteration can continue calculating the "rest"
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 6 years ago.
Improve this question
I have tried to code this problem by converting the looped variables from 100 to 999 to strings, seperate it's digits to numerical values, find the sum of them when cubed, it seems correct when I calculate it on pen and paper, however when I log it it just prints all looped numbers from 100 to 999 , he is my code
for (var i=100; i<=999; i++){
var x = i.toString();
var z = i
var a = parseInt(x[0]);
var b = parseInt(x[1]);
var c = parseInt(x[2]);
var y = (a * a * a) + (b * b * b) + (c * c * c);
if (y = z){console.log ("a happy number is " + x);}
}
Here is a jsfiddle for you JS FIDDLE LINK
for (var i=100; i<=999; i++){
var myString = i.toString();
var a,b,c;
//this is how I would split string apart
a =myString.substring(0,1);
b =myString.substring(1,2);
c =myString.substring(2,3);
var y = (a * a * a) + (b * b * b) + (c * c * c);
//this was your logic error
if (y === i){console.log ("a happy number is " + i);}
}
console.log('done');
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 8 years ago.
Improve this question
The issue I am having is I'm trying to get the alert to tell the person if the random number generated is in the ranges to be an A,B,C,D, or F. All that happens is it says all the numbers are F's not matter what.
var grade = (Math.floor(Math.random() * 100 + 1));
document.write(Math.floor(Math.random() * 100 + 1))
if (grade >= 90) {
alert("A");
} else if (grade >= 80) {
alert("B");
} else if (grade >= 70) {
alert("C");
} else if (grade >= 60) {
alert("D");
} else {
alert("F");
}
The problem is that you're checking a different number than you're writing with document.write here:
var grade = (Math.floor(Math.random() * 100 + 1));
document.write(Math.floor(Math.random() * 100 + 1))
This would need to be:
var grade = (Math.floor(Math.random() * 100 + 1));
document.write(grade);
In order to accurately reflect what is happening.
The problem is that your not generating a random value properly.
Math.random() returns a random number between 0 (inclusive) and 1 (exclusive). Try using this statement.
var grade = Math.floor((Math.random() * 100));
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Problem
The following code compiles with following error:
Unexpected token ) path/file.js:3:296
Code
The following script represents a simple function taking two int arguments, and converting them in some way. I won't go into details as the problem is a syntax error.
PS. I am aware this algorithm doesn't work yet, the problem is pure the error chrome is showing up.
function freeTimeCalculator (fuelPrimary, fuelSecondary) {
var freeTime, secondaryFuel, freeTimeFactor = 0.5, fuelSecondaryFactor = 0.3;
function displayResults() {
// Calculate variables
calculateTime();
// Display results
console.log("Free time: " + freeTime);
return console.log("Secondary fuel: " + secondaryFuel);
}
function calculateTime () {
var hours = [], minutes = [];
// Notice: both arrays and indexes getting tied up
hours[0] = minutes[0] = fuelPrimary.toString();
hours[1] = minutes[1] = fuelSecondary.toString();
// Calculation on strings
// Notice: we take advantage that a notation may contain
// many hours even 100, but the minutes will be always
// the last two numbers.
hours[0] = parseInt(hours[0].substr(0, hours[0].length-2));
minutes[0] = parseInt(hours[0].substr(hours[0].length-2, hours[0].length));
hours[1] = parseInt(hours[1].substr(0, hours[1].length-2));
minutes[1] = parseInt(hours[1].substr(hours[1].length-2, hours[1].length));
// Assigning values to the global variables
freeTime = ((hours[0] * 60 + minutes[0]) * freeTimeFactor);
return secondaryFuel = ((hours[1]) * 60 + minutes[1]) * fuelSecondaryFactor);
}
}
}
Change the last line:
return secondaryFuel = ((hours[1]) * 60 + minutes[1]) * fuelSecondaryFactor);
to
return secondaryFuel = ((hours[1]) * 60 + minutes[1]) * fuelSecondaryFactor;
// ^
EDIT:-
Also the code has extra } brackets. Do remove them. To be precise one extra } bracket at the end
You have a stray ) on the last line. This -
return secondaryFuel = ((hours[1]) * 60 + minutes[1]) * fuelSecondaryFactor);
should be either this -
return secondaryFuel = (hours[1] * 60 + minutes[1]) * fuelSecondaryFactor;
or this -
return secondaryFuel = ((hours[1] * 60 + minutes[1]) * fuelSecondaryFactor);
You have extra ) here
return secondaryFuel = ((hours[1]) * 60 + minutes[1]) * fuelSecondaryFactor);
^