I'm trying to solve a problem and I quote:
"A game needs to be created in which the user attempts to guess a random whole number between 1 and 100. Upon Guessing, the game will tell the user if they need to go higher or lower. If the user guesses the number, the game will tell them they’re right, and how many attempts it took"
I'm trying to attempt this by having a webpage with a prompt asking for the guess, and then if loops deciding if the guess is the same, higher or lower than the random number. However! I've got the prompt to show up, but no matter what number it will always say the numbers correct! Please help!
Here's my html:
<!DOCTYPE html>
<html lang="en">
<script src="Assignment%20Task%202.js"></script>
<body>
PLAY THE GUESSING GAME:
Guess a number between 0 and 1000!
</body>
<br>
<button onclick= "Guessing_game()" >play</button>
<br>
<p>
You have guessed this many times:
</p>
<p id="num_guesses"></p>
</html>
here's my javascript:
var number = Math.floor(Math.random() * 1000) + 1;
var num_guesses = 1;
function Guessing_game() {
var guess;
guess = prompt("what is your guess?");
if (guess = number) {
alert("Good Job! You got the number correct!");
}
if (guess < number) {
num_guesses = +1;
alert("Bad luck! You need to guess lower");
}
if (guess > number) {
num_guesses = +1;
alert("Bad luck! You need to guess higher");
}
document.getElementById("num_guesses").innerHTML = num_guesses;
}
The problem is with your if (guess = number) line of code.
Using guess = number assigns the number to the guess variable here. If you want to check whether guess is equal to number use guess==number in the if condition like:
if (guess == number)
For more information, you can read it out here.
= is assignment operator.
For e.g var a = "foo";
== is used for value comparison.
For e.g
if(a == "foo") {
// Do something if above condition is true
}
=== is strict comparison, that means value and type should be same .
As others have pointed out, in javascript (and in many other languages):
= is the assignment operator
But the best operator to use (especially in javascript) is not ==.
== indicates that two values are equivalent
Instead, the best operator to use is ===:
=== indicates that two values are identical.
In this case, this is, ideally, what you ought to be using in your script:
if (guess === number) {
[... CODE HERE...]
}
Related
I have an if statement that is supposed to execute code if a variable returns false, but even though I have checked and made sure the variable returns false, the code does not execute. Here is the code:
SOLUTION: i seem to have accidentally misplaced the if statement, and have moved it and fixed the program. thank you everyone who has helped me fix my problem
function letterCheck() {
var wordToGuess = puzzle;
var letterToGuess = guess;
console.log(letterToGuess);
matched = false;
for (x = 0; x < wordToGuess.length; x++) {
if (letterToGuess === wordToGuess[x]) {
console.log('Your guess was correct!');
console.log('You have', 6 - parts, 'incorrect guesses remaining');
blanks[x] = letterToGuess;
console.log(blanks);
var fillBlank = '';
for (y = 0; y < blanks.length; y++) {
fillBlank += blanks[y];
}
document.getElementById('puzzle').innerHTML = fillBlank;
matched = true
win++
if (win === puzzle.length) {
setTimeout(() => alert("You win!"), 100)
}
break;
}
}
}
//this is the if statement that is not working
if (this.matched === false) {
console.log("Your guess was incorrect!");
parts++;
graphics[parts - 1]();
console.log('You have', 6 - parts, 'incorrect guesses remaining');
}
"matched" and "this.matched" are 2 different variables. "matched" is global, "this. matched" is local to the function.
To fix: Use either of "matched" or "this.matched" everywhere - don't mix and match.
Some basic questions need to be asked first. What programming language are you using?
I will assume that you are using JavaScript, because that is the only language that comes to mind that has a === operator. The identity operator === behaves identically to the equality operator == except no type conversion is done. The identity operator requires that all types must be the same types to be considered equal.
Therefore, the == equality operator will compare for equality after doing any necessary type conversions, while the === identity operator will not do the conversion, so if two values are not the same type, the identity operator will simply return false.
Both operators execute at approximately the same speed, so if I were you, I would switch to the equality operator and try again. Let me know what you get!
Reference: http://www.c-point.com/javascript_tutorial/jsgrpComparison.htm
I am making a program that asks the user for 2 numbers ( a and b). Then the program asks them if they want to add, subtract, multiply, or divide, by inputting the number 1 for addition, 2 for subtract, 3 for multiply, and 4 for division. If any other number other than 1-4 is inputted ( say 0) the program must stop, and an alert tells them to re try the calculation. if the user inputted the first 3 numbers correctly, then they should get their computation in an alert box (THIS IS NOT WORKING!).
Then they are asked with a prompt box if they wish to do another computation ( y to continue, anything else ends the program), the prompt shows, but if i input anything the program continues. there is an If else statement within the cont1() function which is called when the user inputs a number corresponding to the arithmetic he/she wishes to complete.
Currently I have no console errors, my first 3 prompt boxes from my getValues() function works properly, but the arithmetic of the add(), subtract, etc functions are not working properly, the alert window never pops up with the answer.
HERE IS MY CODE!(EDITED 3/10/16 10:31)
EDIT: MY if else statement is working now.. But the arithmetic is still not working.
10:31 EDIT: The arithmetic portion is now fixed because i didn't have the parseInt(), but the cont1() function is still executing as true when the input by the user is suppose to stop the prorgam
10:52 edit : With the getValues() function : the function checks to see if a, b and c are numbers, when i input all numbers it returns that they are not numbers. Also got rid of the arithmetic functions, converted them over to a switch statement.
<!DOCTYPE html>
<html lang="en-US">
<title> B_Math Calculator </title>
<head>
<script>
function getValues()
{
var a = parseInt(prompt("please enter the first number"), 1);
var b = parseInt(prompt("please enter the second number"), 2);
var c = parseInt(prompt("please enter 1 to : ADD , 2 to : SUBTRACT, 3 to : MULTIPLY, or 4 to : DIVIDE"), 1);
if(isNaN(a) || isNaN(b) || isNaN(c)){
alert("One or more of your inputs were not numeric!");
}
alert("Answer is: " + calc(a,b,c));
cont1();
}
function calc(oper1, oper2, oper3){
switch (oper3){
case 1:
return oper1 + oper2;
break;
case 2:
return oper1 - oper2;
break;
case 3:
return oper1 * oper2;
break;
case 4:
return oper1 / oper2;
break;
default:
alert("please enter 1 to : ADD , 2 to : SUBTRACT, 3 to : MULTIPLY, or 4 to : DIVIDE, press Click here to do some math!, to try again.");
break;
}
}
// ASK IF USER IS DONE (Y FOR YES , ANYTHING ELSE FOR NO)
function cont1()
{
var answ = prompt("Next computation? Y : yes, any other letter for no.");
if(answ.toLowerCase() === "y") {
getValues();
} else {
alert("thank you for using my calculator!");
}
}
</script>
</head>
<body>
<button onclick="getValues()" value="Call Function"> Click here to do some math! </button>
</body>
</html>
This is the correct way to accomplish what you want:
if(c==1) {
add(a,b);
} else if(c==2) {
subtract(a,b);
} else if(c==3) {
multiply(a,b);
} else if(c==4) {
divide(a,b);
} else {
alert("please enter 1 to : ADD , 2 to : SUBTRACT, 3 to : MULTIPLY, or 4 to : DIVIDE, press Click here to do some math!, to try again.");
}
Or, better yet:
switch (c){
case 1:
add(a,b);
break;
case 2:
subtract(a,b);
break;
case 3:
multiply(a,b);
break;
case 4:
divide(a,b);
break;
default:
alert("please enter 1 to : ADD , 2 to : SUBTRACT, 3 to : MULTIPLY, or 4 to : DIVIDE, press Click here to do some math!, to try again.");
break;
}
Which is a much cleaner way to structure an if/else that only takes a single expression into account.
In either case, proper indentation makes the code much more readable.
You also have problems with the location of your return statements in that you have more code that comes after them. A return statement doesn't just return a value to the caller, but it also returns programmatic control to the caller, meaning that your function ENDS when it encounters return. So, in your case, no code that comes after the return will be processed.
Additionally, in your cont1() function, your test is:
if(answ = "y")
This is not testing answ to see if it has a value of "y", the single equal sign is assigning the value of "y" to answ, which is an operation that evaluates to true, meaning that you will always execute the code in the true branch. You need to use double (==) or triple (=== for equality without conversion) to compare values.
As I've mentioned, proper code formatting is important, not only for readability, but for processing. Opening curly braces should appear at the end of the line for which they belong. This:
function foo()
{
and this:
if(condition)
{
true code
}
else if (condition)
{
Should be:
function foo() {
and this:
if(condition) {
true code
} else if (condition) {
As a side note, your code assumes that the user input will be numeric, which is wrong for two reasons.
A prompt ALWAYS returns a string, regardless of the input.
The user might (will) type something unexpected, like "one"
Before operating on the input, you should check it. There are many techniques for determining if input is numeric (many have pros and cons), but something along the lines of the following would be appropriate:
var a = parseInt(prompt("please enter the first number"),10);
var b = parseInt(prompt("please enter the second number"),10);
var c = parseInt(prompt("please enter 1 to : ADD , 2 to : SUBTRACT, 3 to : MULTIPLY, or 4 to : DIVIDE"),10);
if(isNaN(a) || isNaN(b) || isNaN(c)){
alert("One or more of your inputs were not numeric!");
}
Lastly, instead of having 4 separate functions that largely do the same thing and decide which one to call with an if or switch, why not just have one function that decides what math to do based on an input parameter.
See this fiddle for a complete solution that incorporates all these points, using switch: https://jsfiddle.net/m0r5r4dx/17/
(c!=1,2,3,4)
The comma operator returns whatever is on the right hand side, so this evaluates as:
(false,2,3,4)
which evaluates as:
4
Use an array if you want to tell if a value isn't in a set.
if ( -1 == [1, 2, 3, 4].indexOf(c) )
else if (c!=1,2,3,4)
This isn't doing what you think it's doing. What this is doing is:
Checking if c isn't equal to 1.
Checking if 2 is truthy (which it is).
Checking if 3 is truthy (which it is).
Checking if 4 is truthy (which it is).
Due to the commas, the value returned is actually 4 (meaning the if statement ignores the first 3 anyway).
What you need to do is change this else clause to:
if (c != 1 && c != 2 && c != 3 && c != 4)
Or:
if (c < 1 || c > 4)
I suggest you take a look at MDN's notes on if...else before doing anything else.
As other answers have mentioned, your method of checking if c is 1, 2, 3, or 4 is incorrect, but you don't actually need your last else if to be an else if, as by the time you've reached it you already know that c is not 1, 2, 3, or 4. You could replace it with an else, and it should work.
Also, your various functions have code after the return that will never execute, as the function finishes as soon as it reaches a return. Since you aren't actually doing anything with the value you return, you should probably remove the return statements.
I'm trying to learn and practice javascript on my own and I've made a bit of progress but I can still get stuck with elementary problems. I think my code is really close to giving me the correct answer but I fail to see what issue I'm missing. If someone better at coding would please take a second and fill me in on what logic error I have, I would be greatly appreciative!
<script>
//2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
var input = 11;
function smallestMultiple(){
for(var i = 2; i <= 10; i++){
if(input % i === 0 && isDivisible(input))
alert(input);//this should only alert when input is divisible by all numbers between 2 and 10
}else{
input ++;
//if input isn't divisible by all numbers between 2 and 10, increment input by 1
}
}
};
// The following function should return true when "input" is divisible by 10, which is the trigger for alerting "input"
function isDivisible(input){
if(input % 10 === 0){
return true;
}else{
return false;
}
};
smallestMultiple();
</script>
Your script is going to find the smallest integer that's divisible both by 10 and a number in 2,3,...,9, which is not what you need.
The faster implementation would probably be setting a couple of temporary divisors that shrinks until the left edge surpass the right one ...
The simplest instead is just selecting a number in 1,2,3...,9, then try to divide it for every number in 1,2,3...,9
The following html sandbox (to remain on-topic) would probably help you to understand.
<html>
<head>
<meta charset="utf8">
</head>
<body>
<div>
<p class="output"></p>
</div>
<script>
window.onload = function() {
function smallest_shared_multiple(from, to) {
var tmp_divisor = from
var tmp_candidate = tmp_divisor
for(;tmp_divisor < to +1;) {
if (tmp_candidate % tmp_divisor) {
tmp_divisor = from
tmp_candidate++
} else {
tmp_divisor++
}
}
return tmp_candidate
}
document.querySelector('p.output').innerHTML =
'For the given range, the smallest shared multiple is ' +
smallest_shared_multiple(1, 10)
}
</script>
</body>
</html>
edit: Please, consider to indent your code before posting. Moreover, as a general rule of programming, it's better naming functions in way that's evocative to what they're supposed to do. ..and make variables' scope the smallest you can. :)
I have been using this function for calculating factorial numbers in JavaScript:
var f = [];
function factorial (n) {
if (n == 0 || n == 1)
return 1;
if (f[n] > 0)
return f[n];
return f[n] = factorial(n-1) * n;
}
All seemed to be going well until I tried the number 500. It returned infinity.
Is there a way that I can prevent infinity as an answer?
Thank you.
You indeed need to use bignumbers. With math.js you can do:
// configure math.js to work with enough precision to do our calculation
math.config({precision: 2000});
// evaluate the factorial using a bignumber value
var value = math.bignumber(500);
var result = math.factorial(value);
// output the results
console.log(math.format(result, {notation: 'fixed'}));
This will output:
1220136825991110068701238785423046926253574342803192842192413588385845373153881997605496447502203281863013616477148203584163378722078177200480785205159329285477907571939330603772960859086270429174547882424912726344305670173270769461062802310452644218878789465754777149863494367781037644274033827365397471386477878495438489595537537990423241061271326984327745715546309977202781014561081188373709531016356324432987029563896628911658974769572087926928871281780070265174507768410719624390394322536422605234945850129918571501248706961568141625359056693423813008856249246891564126775654481886506593847951775360894005745238940335798476363944905313062323749066445048824665075946735862074637925184200459369692981022263971952597190945217823331756934581508552332820762820023402626907898342451712006207714640979456116127629145951237229913340169552363850942885592018727433795173014586357570828355780158735432768888680120399882384702151467605445407663535984174430480128938313896881639487469658817504506926365338175055478128640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
500! is, for lack of a better term, "[bleep]ing huge".
It is far, far beyond what can be stored in a double-precision float, which is what JavaScript uses for numbers.
There's no way to prevent this, other than use numbers that are reasonable :p
EDIT: To show you just how huge it is, here's the answer:
500! = 1220136825991110068701238785423046926253574342803192842192413588385845373153881997605496447502203281863013616477148203584163378722078177200480785205159329285477907571939330603772960859086270429174547882424912726344305670173270769461062802310452644218878789465754777149863494367781037644274033827365397471386477878495438489595537537990423241061271326984327745715546309977202781014561081188373709531016356324432987029563896628911658974769572087926928871281780070265174507768410719624390394322536422605234945850129918571501248706961568141625359056693423813008856249246891564126775654481886506593847951775360894005745238940335798476363944905313062323749066445048824665075946735862074637925184200459369692981022263971952597190945217823331756934581508552332820762820023402626907898342451712006207714640979456116127629145951237229913340169552363850942885592018727433795173014586357570828355780158735432768888680120399882384702151467605445407663535984174430480128938313896881639487469658817504506926365338175055478128640000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
That right there is a 1,135-digit number. For comparison, double-precision floats can handle about 15 digits of precision.
You could consider using an arbitrary precision numeric library. This is a question of its own, though. Here's one related question: https://stackoverflow.com/questions/744099/is-there-a-good-javascript-bigdecimal-library.
I dont know if anyone has solved this elsewise...
I'm a novice beginner in coding and dont know all the aspects. But after I faced this factorial problem myself, i came here when searching for the answer. I solved the 'infinity' display problem in another way. I dont know if its very efficient or not. But it does show the results of even verry high intergers.
Sorry for any redundancy or untidiness in the code.
<!DOCTYPE html>
<html>
<head>
<title>Factorial</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<input type='text' id='number' />
<input type='button' value='!Factorial!' id='btn' />
<script>
var reslt=1;
var counter=0;
var mantissa=0; //stores the seperated matissa
var exponent=0; //stores the seperated exponent
$(document).ready(function (){
$('#btn').click(function (){
var num=parseFloat($('#number').val()); //number input by user
for(i=1;i<=num;i++){
reslt=reslt*i;
//when the result becomes so high that the exponent reaches 306, the number is divided by 1e300
if((parseFloat(reslt.toExponential().toString().split("e")[1]))>=300){
reslt=reslt/1e300; //the result becomes small again to be able to be iterated without becoming infinity
counter+=1; //the number of times that the number is divided in such manner is recorded by counter
}
}
//the mantissa of the final result is seperated first
mantissa=parseFloat(reslt.toExponential().toString().split("e")[0]);
//the exponent of the final result is obtained by adding the remaining exponent with the previously dropped exponents (1e300)
exponent=parseFloat(reslt.toExponential().toString().split("e")[1])+300*counter;
alert(mantissa+"e+"+exponent); //displays the result as a string by concatenating
//resets the variables and fields for the next input if any
$('#number').val('');
reslt=1;
mantissa=0;
exponent=0;
counter=0;
});
});
</script>
</body>
</html>
Javascript numbers can only get so big before they just become "Infinity". If you want to support bigger numbers, you'll have to use BigInt.
Examples:
// Without BigInt
console.log(100 ** 1000) // Infinity
// With BigInt
// (stackOverflow doesn't seem to print the result,
// unless I turn it into a string first)
console.log(String(100n ** 1000n)) // A really big number
So, for your specific bit of code, all you need to do is turn your numeric literals into BigInt literals, like this:
var f = [];
function factorial (n) {
if (n == 0n || n == 1n)
return 1n;
if (f[n] > 0n)
return f[n];
return f[n] = factorial(n-1n) * n;
}
console.log(String(factorial(500n)));
You'll find that you computer can run that piece of code in a snap.
Hi this is due to the nature of java script as it can't represents number above 253-1 reference so to solve this either wrap the number with BigInt(n) or add to the number >> 3n
const factorial = (n) => {
n = BigInt(n)
if ( n < 1 ) return 1n
return factorial(n - 1n) * n
}
I'm new to JavaScript.
I've worked my work through Learning JavaScript (o'reilly) but am just trying to make my first JavaScript.
I thought it best to work on something I'm interested in and as it turned out is fairly complicated.
I'm basically trying to simulate (eventually) a situation in Space Hulk (Boardgame) where a Genestealer has 12 steps between him and the Space Marine.
On the first step its 6 on either dice to kill the Genestealer, and after that 5 or 6 to kill.
The gun jams if the number on the dice is the same.
I'm just trying to emulate the first step here. I think the problem is with jamCheck.
Basically this outputs as always true, even if I change it to != it always shows gun jammed.
I wondered if the variable needed to be passed into another local variable, but it works for killCheck without having to do this. (and I tried it, although I may be doing it wrong)
It is completely possible there is something really simple wrong here.
I hope you can help, or point me in the right direction.
Many thanks!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>SH</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
//<![CDATA[
function diceRoll1() {
iValue = Math.random(); // random number between 0 and 1
iValue *= 6; // multiply by 6 to move the decimal
iValue = Math.floor(iValue)+1; // round to nearest integer. +1 to 1-6.
var roll1 = iValue;
document.getElementById('result1').innerHTML = 'Dice roll 1 : ' + roll1;
killCheck (roll1);
jamCheck (roll1);
return;
}
function diceRoll2() {
iValue = Math.random(); // random number between 0 and 1
iValue *= 6; // multiply by 6 to move the decimal
iValue = Math.floor(iValue)+1; // round to nearest integer. +1 to 1-6.
var roll2 = iValue;
document.getElementById('result2').innerHTML = 'Dice roll 2 : ' + roll2;
killCheck (roll2);
jamCheck (roll2);
return;
}
function killCheck(roll1,roll2){
if (roll1==6 || roll2==6)
{
document.getElementById('kill').innerHTML = 'GS KILLED';
}
return;
}
function jamCheck(roll1,roll2){
if (roll1 == roll2)
{
document.getElementById('jam').innerHTML = 'GUN JAMMED';
}
return;
}
//]]>
</script>
</head>
<body onload="diceRoll1();diceRoll2();killCheck();jamCheck();">
<p id="result1">Dice roll 1</p>
<p id="result2">Dice roll 2</p>
<p id="kill">GS ALIVE</p>
<p id="jam">GUN FINE</p>
</body>
</html>
EDIT: I eventually got there with a lot of help from a friend; here is the current code:
...
function getDiceValue() {
var diceValue = Math.random();
diceValue *= 6;
diceValue = Math.floor(diceValue) + 1;
return diceValue;
}
function killCheck(roll1, roll2) {
if (roll1 === 6 || roll2 === 6) {
document.getElementById('kill').innerHTML = 'GS KILLED';
}
return;
}
function jamCheck(roll1, roll2){
if (roll1 === roll2) {
document.getElementById('jam').innerHTML = 'GUN JAMMED';
}
return;
}
function rollDice() {
var roll1 = getDiceValue(),
roll2 = getDiceValue();
document.getElementById('result1').innerHTML = 'Dice roll 1 : ' + roll1;
document.getElementById('result2').innerHTML = 'Dice roll 2 : ' + roll2;
killCheck (roll1, roll2);
jamCheck (roll1, roll2);
}
//]]>
...
<body onload="rollDice();">
Math.floor() rounds down (think about the name... ceil rounds up) if you REALLY want to round to the "nearest" integer you need to use Math.round().
In your case if you multiply by 6 and round down you'll never get a number higher than 5.
I suspect this is your problem, though I only glanced at your code, so, forgive me if that's just one mistake and not the cause of your issue.
[Edit] upon further reflection, disregard the above. The problem is that your methods expects 2 parameters but you're only passing in one.
I think you're misunderstanding the way parameter passing works.
jamCheck(p1, p2){} what you name these is not relevant. These labels only exist INSIDE your method. I suspect that what is confusing you is that you're using the same labels for the variables you're passing in, as well as the ones in your method. So, when you call the method jamCheck(roll1) it can't do what it needs to cause it's designed to work on 2 variables. Beyond that whatever result you're getting is just the browser trying to make up for code whose syntax is broken. In languages like C or Java you wouldn't even be able to compile such code; You'd be pointed at these lines as not making any sense, by the compiler.
So, the solution is (something like)...
var roll1,roll2;
roll1 = diceRoll1();
roll2 = diceRoll2();
jamCheck(roll1,roll2);
killCheck(roll1,roll2);
But in your diceRoll methods the last thing you'll need to do is return roll1; (or roll2 respectively)
And look to kirean's answer for how to wrap this all up in an init method, so that you're not calling 4 (or more) methods from the body's onload callback.
Youre doing a couple things wrong here, the first is confusing function scoped variables with global scoped variables.
this function
function jamCheck(roll1,roll2){
if (roll1 == roll2)
{
document.getElementById('jam').innerHTML = 'GUN JAMMED';
}
return;
}
expects two parameters, but you are passing in none here body onload="...jamcheck()"
as a result, undefined is equal to undefined, so of course its true.
You need a wrapper function similar to this
function executeGame(){
var dice1 = rollDice1();
var dice2 = rollDice2();
jamCheck(dice1, dice2)
}
And then call this function on body onload.