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;
}
Related
In my current project, I am creating random mathematics questionnaires for abacus student. So the exam page will serve sums one by one. Based on the student level I am generationg sums at front end using jquery and rendering to get student answer for validation. In a particular level I need to generate divisions with zero remainder.
So, I am using below function to generate the sum which is returning undefined sometimes.
tripleDigitSingleDigitWithoutRemainder: function()
{
var dividend = BOBASSESSMENT.general.randomIntFromInterval(100, 999);
var divisor = BOBASSESSMENT.general.randomIntFromInterval(2, 9);
console.log("out: " + dividend + "_" + divisor);
console.log("remainder: " + (dividend % divisor));
var result_val = "";
// result_val = dividend % divisor;
if(dividend % divisor != 0)
{
console.log('loop_again');
BOBASSESSMENT.general.tripleDigitSingleDigitWithoutRemainder();
}else{
result_val = dividend + "_" + divisor;
console.log("return: " + result_val);
}
console.log("final_return: " + result_val);
return result_val;
}
hence, please help me here to do further.
the requirement is to show question one by one and I need a dividend value and divisor value which does give remainder as 0. It means 16 % 2 = 0 not like 16 % 3 = 1.
Can you please some one help here.
As discussed in the comments here's a way to use a loop to try again with different values instead of recursion:
tripleDigitSingleDigitWithoutRemainder: function()
{
for(;;)
{
var dividend = BOBASSESSMENT.general.randomIntFromInterval(100, 999);
var divisor = BOBASSESSMENT.general.randomIntFromInterval(2, 9);
if(dividend % divisor == 0)
{
var result_val = dividend + "_" + divisor;
console.log("return: " + result_val);
return result_val;
}
}
}
Here we have an infinite loop and we keep looping until we have a valid problem and then immediately return when we do. for(;;) is one way of writing an infinite loop: there are others e.g. while (true) { ... } if that's clearer - up to you.
(However I prefer the approach in Wimanicesir's answer which constructs a correct value rather than just trying repeatedly until we find one, which may take many more goes.)
As said in the comments. Isn't it better to just create a working division by creating it with a product?
function generate() {
// Numbers [2-9]
var small = Math.floor(Math.random() * 8) + 2
// This will give the limit of current divider
var limit = Math.ceil(900 / small)
// We check the minimum now
var minimum = Math.floor(100 / small)
// We create a new random with given limit
var big = Math.ceil(Math.random() * limit) + minimum
// Create the product
var product = big * small;
return { question: product + ' / ' + small, answer: big }
}
console.log(generate())
Hey I'm trying to complete a task it was given at school and I am hitting a wall I have only been learning JavaScript for about 2 days so excuse me if the answer is right in front of my face any and all help is welcome. Below is the instruction given and below the instruction is where I am at with my JavaScript. The problem I am running into is I can't seem to get it to display the cost of the bagels only the amount of bagels themselves I know I am getting close but for the life of me I cannot seem to break through this wall. Thanks in advance and sorry for the blocks of text I am not yet familiar with how to pose questions about these subjects :)
3) calculateBagels
A bagel shop charges 75 cents per bagel for orders of less than a half-dozen bagels and charges 60 cents per bagel for orders of a half-dozen or more bagels. Write a program that requests the number of bagels ordered and displays the total cost.
Test the program for orders of four bagels and a dozen bagels.
function bagelcost(number1){
var result = number1
if(result >= 6){
(result * 0.60)
} else {
(result * 0.75)
}
return result;
}
console.log(bagelcost(100))
You have to store result while multiplication otherwisw it not retain in result variable which you have return
function bagelcost(number1){
var result = number1;
if(result >= 6){
result=result * 0.60;
} else {
result=result * 0.75;
}
return result;
}
console.log(bagelcost(100));
More ever you can directly return result as below
function bagelcost(number1){
if(number1 >= 6){
return number1 * 0.60;
} else {
return number1 * 0.75;
}
}
console.log(bagelcost(200));
You should assign the statements result * 0.60 and result * 0.75 to the result variable
result=result * 0.60;
result=result * 0.75;
You can directly return the calculation. And you can omit the else part, because all code after an if with return is treated as else part. For fixed-point notation use Number.toFixed().
function getBagelCost(count) {
if (count < 6) {
return count * 0.75;
}
return count * 0.6;
}
document.write('$' + getBagelCost(4).toFixed(2) + '<br>');
document.write('$' + getBagelCost(12).toFixed(2) + '<br>');
You were really close.
The key was to save the value. Anything that uses arithmetic like this requires you to capture (assign to a variable, or send as a return value) the result on the left (hence the a = b + c; syntax).
If I might make a suggestion, it might make sense if you use more (and more descriptive) words in your functions.
As you learn (and even as you write software as a day job), it's tempting to use arithmetic everywhere, without much explanation, but it becomes easier to forget what's happening.
The same is true for changing the value multiple times. The more times you save a different value saved at the same name, the less you can tell what's happening when.
function getCostOfBagels (bagelCount) {
var discountPrice = 0.60;
var fullPrice = 0.75;
var discountVolume = 6;
var unitPrice;
if (bagelCount < discountVolume) {
unitPrice = fullPrice;
} else {
unitPrice = discountPrice;
}
var totalCost = bagelCount * unitPrice;
return totalCost;
}
Eventually, you might consider refactoring this kind of code, so that this function only does the calculating:
var discountPrice = 0.60;
var fullPrice = 0.75;
var discountVolume = 6;
function getBagelPrice (unitCount) {
var bagelPrice = (unitCount < discountVolume) ? fullPrice : discountPrice;
return bagelPrice;
}
function getCostOfBagels (bagelCount) {
var unitPrice = getBagelPrice(bagelCount);
var totalCost = bagelCount * unitPrice;
return totalCost;
}
getCostOfBagels(4); // 3.00
getCostOfBagels(12); // 7.20
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.
I am trying to log to the console a message saying : Gratz! You gained 5 points!' after you rolled two the same numbers after each other.
can someone explain me what is wrong with my code?
<script>
var d1 = Math.floor(Math.random()*6) +1;
var diceRolls = [];
function rollDice() {
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random()*6) +1;
console.log("You rolled "+d1+".");
diceRolls.push(d1);
}
if(diceRolls[diceRolls.length - 1] === d1) {
console.log("You won 5 points!");
}
</script>
The problem with your code is that you're checking outside the function, and the condition is not correct. First you need to make sure that the dice has been rolled at least two times, then you compare the two last values. And as #Bergi noted, you also need to call the function, although I guess you're already doing that. Below is the correct solution:
var diceRolls = [];
var totalDiceRolls = 0;
// you set this to whatever you want the limit to be
var maxDiceRolls = 10;
function rollDice() {
if (++totalDiceRolls > maxDiceRolls)
{
alert(maxDiceRolls + " dice rolls allowed at max!");
return;
}
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random()*6) +1;
console.log("You rolled "+d1+".");
diceRolls.push(d1);
if(diceRolls.length > 1 && diceRolls[diceRolls.length - 2] == d1) {
console.log("You won 5 points!");
}
}
You never loop the result, and you assign d1 with a random number, but do nothing with it.
You need to roll the dice and each time, loop the array to find if 2 numbers are the same, at the moment you don't loop, so there is no way to know if 2 numbers are equals.
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: $' + ...);