I am attempting to create a function function examineNumbers(). This function is supposed to prompt the user for numbers on the click of a button. The code is supposed to determine the type of the number as even, odd and float. Then add up all the sums numTotal and floatTotal and the averages numAverage and floatAverage. I actually have two issues. The while loop is not supposed to incorporate the SENTINEL into the code. It adds it in anytime -1 is inputted by the user. It is just supposed to break the while loop.
Second issue is my code fails to add the total correctly. It shows the original value of 0 and displays all other numbers inputted next to the number 0 instead of adding into one sum. This occurs for numTotal and floatTotal. Can anyone help me determine where the issue is on these two items please?
function examineNumbers() {
const SENTINEL = -1;
let number = 0;
let type;
let numValues = 0;
let numAverage = 0;
let floatValues = 0;
let numTotal = 0;
let floatTotal = 0;
let list = document.getElementById("list");
let numbers = document.getElementById("numbers");
let floating = document.getElementById("floating");
// while loop to only allow numbers greater than zero to be inputted
while (number != SENTINEL) {
number = prompt("Enter a number. Type " + SENTINEL + " to stop.");
// deterrmines if a number is even
if (number % 2 == 0) {
type = " is an even value";
numTotal += number;
numValues++;
}
// determines if a number is odd
else if (Math.abs(number % 2) == 1) {
type = " is an odd value";
numTotal += number;
numValues++;
}
// gives a floating point type if above two aren't met
else {
type = " is a floating point value.";
floatTotal += number;
numTotal += number;
numValues++;
floatValues++;
}
let numResults;
let floatResults;
// averages non floating numbers
numAverage = numTotal / numValues;
numResults = document.getElementById("numbers").innerHTML = " The total is " + numTotal +
" and the average is " + numAverage + ".";
// gives value if no non floating numbers are entered
if (numValues == 0 && floatValues == 0) {
numResults = document.getElementById("numbers").innerHTML = " No values were entered."
}
// averages floating point numbers
floatAverage = floatTotal / floatValues;
floatResults = document.getElementById("floating").innerHTML = " The total is " + floatTotal +
" and the average is " + floatAverage + ".";
// gives value if no floating numbers are entered
if (floatValues == 0) {
floatResults = document.getElementById("floating").innerHTML = "No floating-pont values were entered."
}
let li = "";
//only add number and its status to list when number not equal to SENTINEL
if (number !== SENTINEL) {
li = document.createElement("li");
li.innerHTML = number + type;
list.appendChild(li);
// displays information for both non floating numbers and floating numbers
numbers.innerHTML = numResults;
floating.innerHTML = floatResults;
}
}
}
<h1> Number Examination Tool </h1>
<form name="myForm">
<button type="button" onclick="examineNumbers();">Click here to enter numbers </button>
<h3>List of Numbers </h3>
<ul id="list"></ul>
<div id="numbers"></div>
<div id="floating"></div>
</form>
You have to use parseInt and ParseFloat functions in the function to get this working correctly. Also, you have to pass another if condition inside the while loop to prevent the "-1" from adding to the total. Hope the below code helps
function examineNumbers() {
const SENTINEL = -1;
let number = 0;
let type;
let numValues = 0;
let numAverage = 0;
let floatValues = 0;
let numTotal = 0;
let floatTotal = 0;
let list = document.getElementById("list");
let numbers = document.getElementById("numbers");
let floating = document.getElementById("floating");
// while loop to only allow numbers greater than zero to be inputted
while (number != SENTINEL) {
number = prompt("Enter a number. Type " + SENTINEL + " to stop.");
if (number == -1) {
break;
}
// deterrmines if a number is even
if (number % 2 == 0) {
type = " is an even value";
numTotal += parseInt(number);
numValues++;
}
// determines if a number is odd
else if (Math.abs(number % 2) == 1) {
type = " is an odd value";
numTotal += parseInt(number);
numValues++;
}
// gives a floating point type if above two aren't met
else {
type = " is a floating point value.";
floatTotal += parseFloat(number);
numTotal += parseFloat(number);
numValues++;
floatValues++;
}
let numResults;
let floatResults;
// averages non floating numbers
numAverage = numTotal / numValues;
numResults = document.getElementById("numbers").innerHTML = " The total is " + numTotal.toFixed(2) +
" and the average is " + numAverage + ".";
// gives value if no non floating numbers are entered
if (numValues == 0 && floatValues == 0) {
numResults = document.getElementById("numbers").innerHTML = " No values were entered."
}
// averages floating point numbers
floatAverage = floatTotal / floatValues;
floatResults = document.getElementById("floating").innerHTML = " The total is " + floatTotal.toFixed(2) +
" and the average is " + floatAverage + ".";
// gives value if no floating numbers are entered
if (floatValues == 0) {
floatResults = document.getElementById("floating").innerHTML = "No floating-pont values were entered."
}
let li = "";
//only add number and its status to list when number not equal to SENTINEL
if (number !== SENTINEL) {
li = document.createElement("li");
li.innerHTML = number + type;
list.appendChild(li);
// displays information for both non floating numbers and floating numbers
numbers.innerHTML = numResults;
floating.innerHTML = floatResults;
}
}
}
<h1> Number Examination Tool </h1>
<form name="myForm">
<button type="button" onclick="examineNumbers();">Click here to enter numbers </button>
<h3>List of Numbers </h3>
<ul id="list"></ul>
<div id="numbers"></div>
<div id="floating"></div>
</form>
Maybe you can learn something from the code below:
//<![CDATA[
/* js/external.js */
let doc, htm, bod, nav, M, I, mobile, S, Q, hC, aC, rC, tC; // for use on other loads
addEventListener('load', ()=>{
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
hC = function(node, className){
return node.classList.contains(className);
}
aC = function(){
const a = [...arguments];
a.shift().classList.add(...a);
return aC;
}
rC = function(){
const a = [...arguments];
a.shift().classList.remove(...a);
return rC;
}
tC = function(){
const a = [...arguments];
a.shift().classList.toggle(...a);
return tC;
}
// magic under here - you can put code below on another page using a load event - except the `}); // end load`
const nums = I('nums'), calc = I('calc'), res = I('res'), evens_sum = I('evens_sum');
const evens_avg = I('evens_avg'), odds_sum = I('odds_sum'), odds_avg = I('odds_avg');
const int_sum = I('int_sum'), int_avg = I('int_avg'), dec_sum = I('dec_sum');
const dec_avg = I('dec_avg'), sum = I('sum'), avg = I('avg'), error = I('error');
function testNums(){
for(let n of arguments){
if(n === '' || isNaN(n)){
return false;
}
}
return true;
}
const calcNums = (()=>{
const eve = [], odd = [], dec = [];
let c, d, n;
return ()=>{
if(hC(error, 'hid')){
c = d = 0; nums.value = nums.value.trim()
eve.splice(0); odd.splice(0); dec.splice(0);
const a = nums.value.split(/\s*,\s*/g);
for(let s of a){
n = +s;
if(n % 1 !== 0){
c = s.replace(/^.*\./, '').length; dec.push(n);
if(c > d)d = c;
}
else if(n % 2 === 0){
eve.push(n);
}
else{
odd.push(n);
}
}
let eL = eve.length, oL = odd.length, iL = eL+oL, dL = dec.length, tL = iL+dL;
const eT = eve.reduce((a, v)=>a+v, 0), oT = odd.reduce((a, v)=>a+v, 0);
const dT = dec.reduce((a, v)=>a+v, 0), iT = eT+oT, tT = iT+dT;
evens_sum.textContent = eT; odds_sum.textContent = oT; int_sum.textContent = iT;
dec_sum.textContent = dT.toFixed(d); sum.textContent = tT.toFixed(d);
evens_avg.textContent = eL === 0 ? 0 : (eT/eL).toFixed(d);
odds_avg.textContent = oL === 0 ? 0 : (oT/oL).toFixed(d);
int_avg.textContent = iL === 0 ? 0 : (iT/iL).toFixed(d);
dec_avg.textContent = dL === 0 ? 0 : (dT/dL).toFixed(d);
avg.textContent = tL === 0 ? 0 : (tT/tL).toFixed(d);
rC(res, 'hid');
}
}
})();
nums.oninput = function(){
let v = this.value.trim();
aC(res, 'hid');
if(v.length && testNums(...v.split(/\s*,\s*/g))){
f = aC;
}
else{
f = rC;
}
f(this, 'yes'); f(error, 'hid');
}
calc.onclick = calcNums;
nums.onkeyup = e=>{
if(e.key === 'Enter')calc.click();
}
}); // end load
/* css/external.css */
*{
padding:0; margin:0; font-size:0; border:0; box-sizing:border-box; outline:none;
overflow:hidden; -webkit-tap-highlight-color:transparent;
}
html,body,.main{
width:100%; height:100%;
}
.main{
background:#aaa;
}
.bar{
position:relative; width:100vw; height:39px; background:#ccc; color:#000;
padding:3px 3px 3px 7px; border-bottom:1px solid #333;
}
h1{
font:bold 27px Tahoma, Geneva, sans-serif;
}
.guts{
width:100%; height:calc(100% - 39px); padding:5px 10px; overflow-y:auto;
}
.guts>*,.guts>#res *{
font:bold 22px Tahoma, Geneva, sans-serif;
}
.guts>#res>div>span{
color:#147;
}
label{
color:#fff; text-shadow:-1px 0 #000,0 1px #000,1px 0 #000,0 -1px #000; margin-top:
}
label:first-child{
margin-top:0;
}
input,textarea,select{
width:100%; height:38px; background:#fff; color:#000; text-shadow:none;
border:1px solid #c00;
}
input,textarea{
border-radius:3px; padding:5px;
}
input[type=button]{
width:100%; height:auto; background:linear-gradient(#1b7bbb,#147); color:#fff;
font:bold 28px Tahoma, Geneva, sans-serif; padding:5px 10px; border:1px solid #007;
border-radius:5px; margin-top:7px; cursor:pointer;
}
.yes{
border-color:#0c0;
}
#error{
color:#900; font-size:18px; text-align:center;
}
.hid{
display:none;
}
.bottom{
width:100%; height:7px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<div class='bar'><h1>Number Fun</h1></div>
<div class='guts'>
<label for='nums'>Enter Comma Separated Numbers</label><input id='nums' type='text' value='' />
<input id='calc' type='button' value='CALCULATE' />
<div class='hid' id='res'>
<div>evens sum: <span id='evens_sum'></span></div>
<div>evens average: <span id='evens_avg'></span></div>
<div>odds sum: <span id='odds_sum'></span></div>
<div>odds average: <span id='odds_avg'></span></div>
<div>integer sum: <span id='int_sum'></span></div>
<div>integer average: <span id='int_avg'></span></div>
<div>decimal sum: <span id='dec_sum'></span></div>
<div>decimals average: <span id='dec_avg'></span></div>
<div>sum: <span id='sum'></span></div>
<div>average: <span id='avg'></span></div>
</div>
<div id='error'>Comma Separated Numbers Only</div>
<div class='bottom'></div>
</div>
</div>
</body>
</html>
Related
Im creating a guessing game and the user has 5 attempts to make the correct guess. I want to save their previous guesses (inputs) to show it to them. I have been using the snippet below to save one attempt when the user types into an <input> field, but how can I save the next 4 attempts in new variables such as userGuess2, userGuess3, etc.
var userGuess = document.getElementById("inputField").value;
$('#previousGuesses').text(userGuess);
Ok then let's pretend this is your input
<input type="text" id="inputField">
You can create an index that will increment everytime the users presses enter to save another answer
var i=1;
And the id name your autogenerated spans will have
var name = "previousGuesses";
Now on your function you will save the value when the user presses enter like you described and when that happens it will create a new span element where it will display the value stored
function myFunction(){
$("#inputField").keypress(function( event ) {
if ( event.which == 13 || event.which == 9) {
var userGuess = document.getElementById("inputField").value;//get value of the answer
var span = document.createElement('SPAN');//create a new span
span.innerHTML = userGuess + "<br>";//answer value goes here
span.id = name+i;//this is the id of your new span, remember ids are unique so we attach var i to the name var we declared before
document.body.appendChild(span);
//$('#previousGuesses'+i).text(userGuess);
i++;
}
});
}
now call your function
myFunction();
https://jsfiddle.net/kenpy/m16bojhg/4/
You can just simply add an element for the user's last attempts and add to it.
f(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector('.guesses');
var lastResult = document.querySelector('.lastResult');
var lowOrHi = document.querySelector('.lowOrHi');
var guessSubmit = document.querySelector('.guessSubmit');
var guessField = document.querySelector('.guessField');
var guessCount = 1;
var resetButton;
guessField.focus();
function checkGuess() {
var userGuess = Number(guessField.value);
if(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if(userGuess === randomNumber) {
lastResult.textContent = "Good job! You win!";
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = '';
setGameOver();
} else if(guessCount === 10) {
lastResult.textContent = 'Hahaha You suck!';
lowOrHi.textContent = '';
setGameOver();
} else {
lastResult.textContent = "Oops! You're Wrong!";
lastResult.style.backgroundColor = 'red';
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Last guess was too low!';
} else if(userGuess > randomNumber) {
lowOrHi.textContent = 'Last guess was too high!';
}
}
guessCount++;
guessField.value = '';
guessField.focus();
}
guessSubmit.addEventListener('click', checkGuess);
console.log('cheat is: ' + randomNumber);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Play Again?';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas p');
for(var i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
body{
background-image: linear-gradient(to left top, #c6fced, #a3efda, #7fe3c7, #54d5b3, #00c89f);
color: #2F3139;
margin: 10rem auto;
height:50vh;
}
h1 {
font-size: 1.5rem;
}
.lastResult {
color: white;
padding: 3px;
}
button {
margin-left:3rem ;
}
<h3 class="display-4 text-center text-muted text-capitalize"></h3>
<div class="container">
<div class="row">
<div class="col-md-6 ">
<h1 class="text-muted text-capitalize">
<span class="text-primary">JavaScript</span> Number guessing game</h1>
<p class="lead">Simply enter a number between 1 - 100 then click the button</p>
</div>
<div class="col-md-6">
<div class="mt-4 d-inline-block">
<div class="form">
<label for="guessField">Guess a number : </label><input type="text" id="guessField" class="guessField">
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas text-center lead">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
</div>
</div> </div>
</div>
Resource
JavaScript number guessing game
I'm working with JavaScript and am having issues with a couple of for loops at a specific value.
When the slider value is incremented, the amount of pics increase by one and vice versa for when its lowered. However, for a reason I'm unsure of, it will remove one of the pics when the slider is incremented from 9 to 10, and will add one when it's lowered from 10 to 9. This problem doesn't occur anywhere else in the slider, so I'm not sure whats going on.
Here's the code. The picture used isn't attached but the missing image favicon does the same job.
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
var prevnumb = 0;
var num = 2
var numberofdivs = 0;
output.innerHTML = slider.value;
slider.oninput = function() {
prevnum = num;
output.innerHTML = this.value;
num = this.value;
var newnum = num;
var newprevnum = prevnum;
console.log(prevnum, num);
if (prevnum > num) {
for (newnum; newprevnum > newnum; newnum++) {
var element = document.getElementById("id");
element.parentNode.removeChild(element);
}
} else if (num > prevnum) {
for (newprevnum; newnum > newprevnum; newprevnum++) {
var picpol = document.createElement("img");
picpol.src = "polee.png";
picpol.setAttribute("id", "id");
picpol.setAttribute("class", "polio");
document.getElementById("basecontainer").appendChild(picpol);
console.log(picpol);
}
} else {
console.log("no change");
}
}
body {
text-align: center;
}
#basecustom {
text-align: center;
}
.polio {
margin: none;
padding: none;
}
Base Customization
<br>
<br>
<div id="basecustom">
Select your amount of pics
<input type="range" min="2" max="25" value="2" id="myRange">
<p>Value: <span id="demo"></span></p>
<div id="valcont"></div>
<div id="basecontainer">
<img class="polioo" src="polee.png" id="id"><img class="polioo" src="polee.png" id="id">
</div>
</div>
You were missing casting value to int. By default it is string.
num = parseInt(this.value);
Above casting will fix your problem.
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
var prevnumb = 0;
var num = 2
var numberofdivs = 0;
output.innerHTML = slider.value;
slider.oninput = function() {
prevnum = num;
output.innerHTML = this.value;
num = parseInt(this.value);
var newnum = num;
var newprevnum = prevnum;
console.log(prevnum, num);
if (prevnum > num) {
for (newnum; newprevnum > newnum; newnum++) {
var element = document.getElementById("id");
element.parentNode.removeChild(element);
}
} else if (num > prevnum) {
for (newprevnum; newnum > newprevnum; newprevnum++) {
var picpol = document.createElement("img");
picpol.src = "https://www.vyapin.com/blog/wp-content/uploads/2012/07/bullet_04-1.gif";
picpol.setAttribute("id", "id");
picpol.setAttribute("class", "polio");
document.getElementById("basecontainer").appendChild(picpol);
console.log(picpol);
}
} else {
console.log("no change");
}
}
body {
text-align: center;
}
#basecustom {
text-align: center;
}
.polio {
margin: none;
padding: none;
}
Base Customization
<br>
<br>
<div id="basecustom">
Select your amount of pics
<input type="range" min="2" max="25" value="2" id="myRange">
<p>Value: <span id="demo"></span></p>
<div id="valcont"></div>
<div id="basecontainer">
<img class="polioo" src="https://www.vyapin.com/blog/wp-content/uploads/2012/07/bullet_04-1.gif" id="id"/><img class="polioo" src="https://www.vyapin.com/blog/wp-content/uploads/2012/07/bullet_04-1.gif" id="id"/>
</div>
</div>
change num = this.value; to num = parseInt(this.value,10); in your original code, num will be a string. so when it increments to 10, you will get a string '10'. And prevnum is '9'. And if (prevnum > num) { will be true.
Just did a simple game of checkers, got the logic done of jumping or moving the checker pieces.
Now having problems on the actual logic of when a checker piece moves over or jumps over the other checker piece. How do i automatically remove or delete the checker piece that was jumped over?
Thanks so much :)
<html>
<head>
<style>
body { background-color: #D1CDDF; }
p { font-family: Verdana, Geneva, sans-serif;
font-size: 30; }
img { width: 35px;
height: 35px; }
label { font-family: "Lucida Console", Monaco, monospace;
font-size: 15; }
.focused{ border: 2px solid yellow; }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var moves = [];
function saveScore() {
// syntax: $.post(URL,data,callback);
$.post("scores.php",
{
TheFile: $("#filename").val(),
TheMessage: $("#winner").val() + "\r\n"
}
,function(dataFromtheServer) {
$("#result").html(dataFromtheServer);
});
}
function openBoard()
{
$(document).ready(function()
{
var p1Name = document.getElementById("p1name").value;
var p2Name = document.getElementById("p2name").value;
var heading = "<center><p><font color=\"red\"><b>" + p1Name + "</b></font> vs <font color=\"blue\"><b>" + p2Name + "</b></font></p></center>";
var table = $('<table width=500px cellspacing=0px cellpadding=0px border=1px ></table>');
var rc;
var picName;
var picName2;
for( y = 1; y <= 8; y++ )
{
var row = $('<tr></tr>');
for ( var x = 1; x <= 8; x++)
{
rc = y + x;
// creating the images
picName = "p" + 1 + ".png" ;
var pic1 = $('<img>').attr('src',picName);
picName2 = "p" + 2 + ".png";
var pic2 = $('<img>').attr('src',picName2);
if(rc % 2 === 0)
{
if(y === 1 || y === 2 || y === 3)
{
var col1 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
col1.html(pic1);
row.append(col1);
}
else if(y === 6 || y === 7 || y === 8)
{
var col2 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
col2.html(pic2);
row.append(col2);
}
else
{
var col3 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
row.append(col3);
}
}
else
{
var col4 = $('<td align=center height=50px width=50px bgcolor=#C4C160 ></td>');
row.append(col4);
}
}
table.append(row);
}
document.getElementById("bBoard").style.visibility = "hidden";
$('#board').append(heading);
$('#board').append(table);
// setting the listener
$('td').click(function()
{
iAmtheClickListener(this.id);
});
});
}
function iAmtheClickListener(theID)
{
var r = $.inArray(theID,moves); // determine if the id is in the array
var content = $("#"+theID).html();
if( ((r < 0) && (content !== "")) || ((r<0) && (moves.length == 1)) )
{
moves.push(theID);
//change background color
changeBackground("#"+theID,"yellow");
}
else
{
moves.splice(r,1); // to remove
changeBackground("#"+theID,"#4E9660") ;
}
if (moves.length == 2)
{
var destId = moves[1] ;
var srcId = moves[0] ;
var srcImg = $("#" + srcId).html();
$("#" + destId).html(srcImg);
$("#" + srcId).html("");
moves = [] ; // remove all
changeBackground("#"+destId,"#4E9660") ;
changeBackground("#"+srcId,"#4E9660") ;
}
$('#result').html(theID);
}
function changeBackground(theIdUwant, theColor)
{
$(theIdUwant).css("background-color",theColor);
}
</script>
</head>
<body>
<center>
<p>~Checkers~</p>
<table border=1 cellpadding=25px>
<tr><td><label>Player 1: <input type=text id=p1name /></label><br/><br/>
<label>Player 2: <input type=text id=p2name /></label><br/><br/>
<button id="bBoard" onclick="openBoard();">Start Game</button><br/><br/></td>
<td><div class="b" id="board"></div></td>
<td>
<input type=hidden id=filename value="players.txt" />
<label>Register Winner: <input type=text id=winner /></label><br/><br/>
<button id="bReg" onclick="saveScore();">Submit</button><br/><br/>
<div id="result"></div>
</td>
</td></tr>
</table>
</center>
</body>
Suppose jumped piece is at board[row][col], you can assign a value of zero or empty at that particular cell after being jumped:
board[row][col] = EMPTY
I can't figure this problem out, I already checked my code but I don't know what the problem is.
This is the question: A mathematician Ulam proposed generating a sequence of numbers from any positive integer n (n>0) as follows.
if n is 1, it will stop.
if n is even, the next number is n/2.
if n is odd, the next number is 3 * n + 1.
continue with the process until reaching 1.
here some examples for the first few integers.
2->1
3->10->5->16->8->4->2->1
4->2->1
6->3->10->5->16->8->4->2->1
7->22->11->34->17->52->26->13->40->20->10->5->16->8->4->2->1
Sample Run:
Enter Positive Integer: 5
The ulam Number Sequence is : 5->16->8->4->2->1
this is my code...
<!DOCTYPE html>
<html>
<head>
<title>Ulam Number Sequence</title>
</head>
<body>
<form name="myform" onsubmit=" return false">
Enter positive integer: <input type="number" id="num" required>
<button onclick="process()">Process</button>
<button onclick="Reset()">Reset</button>
</form>
<p id = "info"> </p>
<script>
function isOdd(num) {
var odd = true;
for (var i = 0; i <= num; i++) {
if (num % i == 0) {
odd = false;
break;
}
}
return odd;
}
function isEven(num) {
var even = true;
for (var i = 0; i <= num; i++) {
if (num % i == 1) {
even = false;
break;
}
}
return even;
}
function process(){
var n = parseInt(document.getElementById("num").value);
var result1 = [];
for(var i = 0; i <= n; i++){
if(isOdd(i)){
result1[result1.length] = i /2;
}
if(isEven(i)){
result1[result1.length] = 3 * i + 1;
}
if(isOdd(result1)){
result1[result1.length] = result1 / 2;
}
if(isEven(result1)){
result1[result1.length] = 3 * result1 +1;
}
//result1[result1.length] = i * 3 + 1;
document.getElementById("info").innerHTML = result1.join("->");
}
}
function Reset(){
document.getElementById("info").innerHTML = "";
document.getElementById("num").value = "" ;
}
</script>
</body>
</html>
Maybe this is a solution for you (and a little hint):
function process() {
var n = parseInt(document.getElementById('num').value),
result = [n];
if (isFinite(n) && n && n === Math.abs(n)) {
while (n !== 1) {
// basically this is all to do.
n = n % 2 ? 3 * n + 1 : n / 2;
result.push(n);
}
document.getElementById("info").innerHTML = result.join(' > ');
} else {
document.getElementById("info").innerHTML = 'Does not compute!';
}
}
function reset() {
document.getElementById('info').innerHTML = '';
document.getElementById('num').value = ''
}
<form name="myform" onsubmit=" return false">
Enter positive integer: <input type="number" id="num" required>
<button onclick="process()">Process</button>
<button onclick="reset()">Reset</button>
</form>
<p id="info"></p>
Im new in javascript and I'm trying to make a simple currency converter, it is working fine when I select "£Pound" "£Pound" or "£Pound" "R$Real" but when I select "R$Real" "R$Real" runs the "Pound" "R$Real" calculation.
I spent hours trying to figure this out (very frustrating).
How to fix it? Is there another way to do it? (also tried using " if " and " else if " same issue). Thanks!
Here`s the HTML:
<label>Amount:</label>
<input type="text" id="amount" />
<label>From:</label>
<select id="select1">
<option value="pound">£ Pound</option>
<option value="real">R$ Real</option>
</select>
<label>To:</label>
<select id="select2">
<option value="pound">£ Pound</option>
<option value="real">R$ Real</option>
</select>
<input type="button" onClick="calculation()" value="calculate" />
<div id="result"></div>
Here`s the JS:
function calculation() {
var amount = document.getElementById('amount').value;
var currency1 = document.getElementById('select1').value;
var currency2 = document.getElementById('select2').value;
switch((currency1)&&(currency2)){
case "pound":
case "pound":
var y = amount * 1;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "pound":
case "real":
var x = currency2 = 3.40;
var y = amount * x;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real":
case "real":
var y = amount * 1;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real":
case "pound":
var x = currency2 = 3.40;
var y = amount / x;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
}}
To fix your JS do the following:
The issue is that your switch would compute to a single string, and you are using fall-through switch statements, jsFiddle to demonstrate what I mean.
Switch Statement Documentation for JavaScript
function calculation() {
var amount = document.getElementById('amount').value;
var currency1 = document.getElementById('select1').value;
var currency2 = document.getElementById('select2').value;
switch (currency1 + ' ' + currency2) {
case "pound pound":
var y = amount * 1;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "pound real":
var x = currency2 = 3.40;
var y = amount * x;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real real":
var y = amount * 1;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real pound":
var x = currency2 = 3.40;
var y = amount / x;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
}
}
Use the below to display the number and then just put the symbol in front, as this code will add commas and separators in the right spots, including negative.
Format number to currency:
function formatCurrency(num, precision) {
//identify '(123)' as a negative number
if (typeof num == 'string' && num.toString().indexOf('\\(') >= 0) {
num = '-' + num;
}
if (num === '' || (num === '-' && precision === -1)) {
return;
}
// if the number is valid use it, otherwise clean it
if (isNaN(num)) {
// clean number
if (num === '' || (num === '-' && precision === -1)) {
return;
}
if (isNaN(num)) {
num = '0';
}
}
// evalutate number input
var numParts = String(num).split('.');
var isPositive = (num == Math.abs(num));
var hasDecimals = (numParts.length > 1);
var decimals = (hasDecimals ? numParts[1].toString() : '0');
var originalDecimals = decimals;
// format number
num = Math.abs(numParts[0]);
num = isNaN(num) ? 0 : num;
if (precision >= 0) {
decimals = parseFloat('1.' + decimals); // prepend "0."; (IE does NOT round 0.50.toFixed(0) up, but (1+0.50).toFixed(0)-1
decimals = decimals.toFixed(precision); // round
if (decimals.substring(0, 1) == '2') {
num = Number(num) + 1;
}
decimals = decimals.substring(2); // remove "0."
}
num = String(num);
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
}
if ((hasDecimals && precision == -1) || precision > 0) {
num += '.' + decimals;
}
// format symbol/negative
var format = isPositive ? '%s%n' : '(%s%n)';
var money = format.replace(/%s/g, '$');
money = money.replace(/%n/g, num);
return money;
}
console.log(formatCurrency(12002031203120, 2))
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
<style>
body{
background:linear-gradient(3150deg,#7458ff,#a48afc);
background-size: cover;
height: 800px;
display: flex;
align-items: center;
justify-content:center;
}
.col-md-8{
background-color: rgb(183, 170, 170);
padding: 10px 24px;
border-radius: 20px;
width: 490px;
}
.form-group{
width: 100%;
display: flex;
}
input{
width:95%;
color:aliceblue;
height: 40px;
font-size: 1em;
margin: 0.2em 0;
border-radius: 10px;
border: none;
background: #676666;
outline: none;
padding: 0.1em;
}
select{
width: 50%;
height:40px;
font-size: 30px;
cursor: pointer;
background: #039cfb;
outline: none;
color: black;
padding: 0 1em;
border-radius: 10px;
border: none;
}
</style>
</head>
<body>
<div class="col-md-6 well">
<h3 class="text-primary">Javascript - Simple Currency Converter</h3>
<hr style="border-top:1px dotted #ccc;">
<div class="col-md-8">
<h4>Converter</h4>
<hr style="border-top:1px groovy #ccc;"/>
<div class="form-group">
<select onchange="Currency(); Calculate()" class="form-control" id="converter" style="width:30%;">
<option value="Dollar">Dollar</option>
<option value="Pound">Pound</option>
<option value="Euro">Euro</option>
<option value="Yen">Yen</option>
<option value="Yuan">Yuan</option>
</select>
<br />
<input type="number" oninput="Calculate()" class="form-control" id="value1"/>
</div>
<br /><br />
<div class="form-group">
<label>Pak Rupee:</label>
<input type="number" class="form-control" id="value2" disabled="disabled"/>
</div>
</div>
</div>
<script>
function Currency(){
y = document.getElementById("converter").value;
return y;
}
function Calculate(){
y = Currency();
x = document.getElementById("value1").value;
if(x == ""){
document.getElementById("value2").value = "";
}else{
switch(y){
case "Dollar":
document.getElementById("value2").value = x * 215.99;
break;
case "Pound":
document.getElementById("value2").value = x * 72.39;
break;
case "Euro":
document.getElementById("value2").value = x * 63.84;
break;
case "Yen":
document.getElementById("value2").value = x * 0.49;
break;
case "Yuan":
document.getElementById("value2").value = x * 8.20;
break;
}
}
}
</script>
</body>
</html>