I am busy with making an nifty tool that measures click for heart beat(s) and then after then clicks it will tell you endUsers Average Heart Rate.
It works fine, when the 10 clicks are over, it will consider my array and calculate an average and alert(); the user with the average.
What I want to do now is instead of alerting the endUser with their average heart rate, alerting them with a diagnosis. So when average equals a value below 59, it should alert("Your heart is effective and fit"); and if it is above 100 it should alert("Your heart is not effective.."); you get the point.
My problem: I can't seem to figure our where to place the switch statement for this, because the error will either tell me: Can't find the variable (that I want to use in the switch statement) or when I place the switch statement somewhere else, it alerts the user with the default-case..
Should I even be using
av = average /= count;
for my switch statement? All I want it to do is, give out alerts based on the case which is all based on the value of the average.
my codes:
The normal working code without switch statement:
<script>
var lastTapSeconds = 0;
var bpm = 0;
//extra variabelen voor functionaliteit uitbreiding.
var beats = [];
var average = 0;
var count = 0;
var tapDiv = document.getElementById("tapDiv");
$(tapDiv).on('click', function() {
var tapSeconds = new Date().getTime();
bpm = ((1 / ((tapSeconds - lastTapSeconds) / 1000)) * 60);
lastTapSeconds = tapSeconds;
tapDiv.innerHTML = '<h1 style="display:inline;">' + Math.floor(bpm) + '</h1><img style="height:256px;width:256px;" src="img/heart.png"/>';
//extra functionaliteit
beats.push(Math.floor(bpm));
average *= count; //average = average * count
average += Math.floor(bpm); //average = average + count
count++;
average /= count; //average = average / counterIncrement
//als array entries 10 heeft bereikt geef prompt met gemiddelde bpm.
if(beats.length >= 10) {
alert("Your Average Beats Per Minute: " + average);
}
});
</script>
The updated code:
<script>
var lastTapSeconds = 0;
var bpm = 0;
//extra variabelen voor functionaliteit uitbreiding.
var beats = [];
var average = 0;
var count = 0;
var tapDiv = document.getElementById("tapDiv");
$(tapDiv).on('click', function() {
var tapSeconds = new Date().getTime();
bpm = ((1 / ((tapSeconds - lastTapSeconds) / 1000)) * 60);
lastTapSeconds = tapSeconds;
tapDiv.innerHTML = '<h1 style="display:inline;">' + Math.floor(bpm) + '</h1><img style="height:256px;width:256px;" src="img/heart.png"/>';
//extra functionaliteit
beats.push(Math.floor(bpm));
average *= count; //average = average * count
average += Math.floor(bpm); //average = average + count
count++;
average /= count; //average = average / counterIncrement
//als array entries 10 heeft bereikt geef prompt met gemiddelde bpm.
if(beats.length >= 10) {
//alert("Your Average Beats Per Minute: " + average);
var av = average /= count;
switch(av) {
case (average>60 && avarage<100):
alert("From the measurements, we conclude that you have a normal resting heart rate.");
break;
case (average<59):
alert("From the measurements, we conclude that you have an efficient heart function and better cardiovascular fitness.");
break;
case (average>100):
alert("From the measurements, we conclude that your resting heart has an high average, we might be stated as unefficient and not fit.");
break;
default:
alert("Please measure again, your measurements seem unregular.");
break;
}
var bpm = 0;
var average = 0;
}
});
It's better to use multiple if-else statements:
if ( average > 60 && average < 100 )
alert( "From the measurements, we conclude that you have a normal resting heart rate." );
else if ( average < 59 )
alert( "From the measurements, we conclude that you have an efficient heart function and better cardiovascular fitness." );
else if ( average > 100 )
alert( "From the measurements, we conclude that your resting heart has an high average, we might be stated as unefficient and not fit." );
else
alert( "Please measure again, your measurements seem unregular." );
The problem in your code is that values in case are calculated in run time and became equal true or false. So every time default section should be executed
Your switch is wrong. You should read up on using the switch. Each case: part should have one possible value for the variable av. Not a conditional. In your case, for example, av is checked against (average > 60 && average < 100), which is either true or false. So unless av itself is true or false, your switch doesn't make sense.
You should solve this using regular if-statement. It can't be done with a switch.
Related
I have to code a console Bingo game for JavaScript. It is one of some exercices that I have to do before a Bootcamp that I will be taking part of, so take in mind that i'm a newbie.
In case someone doesn't know the game:
You will have a "card" showing 15 numbers (not repeated and random)
Each turn a random number (bingo ball) will be shown.
The numbers are from 1 until 90, so either balls and bingo cards will have these numbers.
When a ball has the same number as one of the numbers from your card, the number of your card will be changed to an 'X'.
Now that I've explained it, my problem is the following:
I have a function to generate generate a ball with a random number each turn. In order to know if a number was already out or not, I've created an array to push the numbers that were already out. This way we can make a loop with an if condition to check if the ball has the same value as the arrays[i] number.
The way I've done it, starts well, but ends up messing the chrome's console... as close as it gets to have the 90 numbers in the array, it starts to iterate the array and generate random numbers until it finds the lasts numbers remaining.
I will paste the part of the code I'm talking about here below.
function bingo(){
console.table(bingoCard);
bombo();
for (let i = 0; i < bingoCard.length; i++){
if (bola === bingoCard[i].number){
bingoCard[i].number = 'X';
bingoCard[i].matched = true;
}
}
continuar = confirm('¿Continuar?');
if (continuar === true){
console.table(bingoCard);
bingo();
}else {
return 'Hasta la próxima';
}
}
function randomNum(){
let min = 1;
let max = 90;
return Math.floor(Math.random() * (max - min) + min);
}
function bombo(){
bola = randomNum();
console.log(+ bola + 'antes de bucle'); //test
for (let i = 0; i < numbersOut.length; i++){
if (bola === numbersOut[i]){
bingo();
}
}
numbersOut.push(bola);
console.log(numbersOut);
alert('Ha salido el número ' + bola);
}
You can instead create an array with numbers from 1 to 90 and random shuffle it.
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modern_method - if you want to understand this method
all! recently i've been trying to build a mercende prime number producer/generator, using the lucas lehmer method of testing. the code works for the first 4 numbers, and then fails for the rest. any suggestions? thanks!
var totalPrimes = Math.floor(prompt("What would you like the upper limit of
our search for primes to be?"));
for (var i = 2; i < totalPrimes; i++) {
var lucasNum = 4;
var curNumber = (Math.pow(2, (i+1))-1);
for (var x = 0; i-1 > x; x++) {
if (lucasNum / curNumber > 1) {
lucasNum = (Math.pow(lucasNum, 2)-2);
} else {
lucasNum = (Math.pow(lucasNum, 2)-2);
}
}
if (lucasNum % curNumber === 0) {
console.log("The number " + curNumber + " is prime");
} else {
console.log("The number " + curNumber + " is not prime");
}
}
The mantissa (or significand) of a Javascript number is 53-bit wide. Therefore, the biggest integer that can be stored in full precision is:
2^53 - 1 = 9007199254740991 = Number.MAX_SAFE_INTEGER
(You may want to read this page for more details.)
Your algorithm is likely to hit this limit very quickly. The precision explosion occurs within this statement:
lucasNum = (Math.pow(lucasNum, 2)-2);
which is included in a loop.
I need to write a piece of code that requests a value for the number of years of a contract. Then use a for loop to calculate a discount factor of 2% per year, i.e. if it is a one year contract, the price will be 98% of the full price, if it is a two year contract, the price will be 96% of the full price, and so on.
I seem to be a little stuck and not sure if I have totally grasped what they are asking.
Here is what I have already done:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transition//EN" "http://www.w3.org/TR/xhtml/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<script type = "text/javascript">
var stringVariable = prompt ("Enter the number of people")
var numberVariable
var loopCounter = prompt ("How many years?");
var numberCount = new Array(100/2);
if (stringVariable <= 30) {
numberVariable = 15*stringVariable;
}
else if (stringVariable> 30 && stringVariable<60) {
numberVariable = 12*stringVariable;
}
else if (stringVariable>60) {
numberVariable =12*stringVariable;
}
alert ("Total cost is: $" + numberVariable);
for (loopCounter = 0; loopCounter <= 4; loopCounter++)
{
document.write("Total discount $" + loopCounter - numberCount[loopCounter] + "<br />");
}
alert ("Total cost is: $" + numberVariable - numberCount);
</script>
</body>
</html>
Thanks in advance for any help.
Your code seems to be fundamentally flawed in a few places, especially your variable names.
Here's how I'd tackle the problem:
// parseInt() converts strings into numbers. 10 is the radix.
var num_people = parseInt(prompt('Enter the number of people'), 10);
var num_years = parseInt(prompt('How many years?'), 10);
// Initialize your variables.
var cost = 0;
var discount = 1.00;
// Your if condition was a bit odd. The second part of it would be
// executed no matter what, so instead of using else if, use an
// else block
if (num_people <= 30) {
cost = 15 * num_people;
} else {
cost = 12 * num_people;
}
alert('Total cost is: $' + cost);
// Here is a for loop. i, j, k, ... are usually
// used as the counter variables
for (var i = 0; i < num_years; i++) {
// Multiplying by 0.98 takes 2% off of the total each time.
discount *= 1.00 - 0.02;
// You fill the rest of this stuff in
document.write('Total discount $' + ... + '<br />');
}
// And this stuff
alert('Total cost is: $' + ...);
I have been programming the following function and have understood everything up until this line.
cost += nightSurcharge;
I am using conditionals in my if statement that are used to add the nightSurcharge to the cost between 8pm and 6am.
What I need to understand is whether the += is simply saying add the nightSurcharge to cost if the condition is met?
// add a parameter called hourOfDay to the function
var taxiFare = function (milesTraveled, hourOfDay) {
var baseFare = 2.50;
var costPerMile = 2.00;
var nightSurcharge = 0.50; // 8pm to 6am, every night
var cost = baseFare + (costPerMile * milesTraveled);
// add the nightSurcharge to the cost starting at
// 8pm (20) or if it is before 6am (6)
if (hourOfDay >= 20 || hourOfDay < 6) {
cost += nightSurcharge;
}
return cost;
};
What I need to understand is whether the += is simply saying add the nightSurcharge to cost if the condition is met?
Yes, that is exactly correct. This code is equivalent:
if (hourOfDay >= 20) {
cost = cost + nightSurcharge;
}
else if (hourOfDay < 6) {
cost = cost + nightSurcharge;
}
How do I get cart checkout price exact to the penny using Javascript?
Right now after taking out all of the trial .rounds etc I was trying.. I am coming up 1.5 cents too high using a high 15 products/prices to test.
for (var i = 0; i < Cookie.products.length; i++) {
boolActive = Cookie.products[i].og_active;
if (boolActive)
{
itemPrice = Cookie.products[i].price;
itemQty = Cookie.products[i].quantity;
itemDiscountPercent = Cookie.products[i].discount_percent;
subtotal = itemPrice * itemQty;
priceDiscount = (subtotal * itemDiscountPercent);
discountAmount += priceDiscount;
}
}
if (!isNaN(discountAmount))
{
var newCartTotal = (cartTotal - priceDiscount);
alert("New Cart Total: " + newCartTotal);
}
var newCartTotal = (cartTotal - pricediscount).toFixed(2)
that will give you the value, but it will be a string. If you need it to stay numeric, use:
var newCartTotal = ((cartTotal - pricediscount * 100) << 0) / 100;
You need to round the discount for each line item: priceDiscount = round_to_hundredth(subtotal * itemDiscountPercent)
Note that this result may not agree with the result you'd get if you add the unrounded results and then round the sum. However, this is the way invoices usually work when calculated by hand (especially since each item can have a different discount percent, so the discount is calculated for each line).
I think you left out a line saying discountAmount += priceDiscount.
modify your code to :
priceDiscount = parseFloat( (subtotal * itemDiscountPercent).toFixed(2) );
and:
newCartTotal = parseFloat( (cartTotal - priceDiscount).toFixed(2) );