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: $' + ...);
Related
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 having an issue with getting the average of the numbers that are inputted through a prompt window. I need to display the numbers like i have so far, but I can't seem to get them to add together to get the average.
here is my code so far.
<html>
<body>
<script type="text/javascript">
function show_prompt() {
i = 0;
do {
var number = prompt("Please Enter a Number");
var number = parseInt(number);
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
}
show_prompt();
var avrg = number + number + number + number + number
document.write('Average of scores : ' + avrg);
</script>
</body>
</html>
You have to move calculation inside function. Also you can do it simplier:
function show_prompt() {
var i = 0;
var sum = 0;//declare a variable to keep the sum of numbers
do {
var number = prompt("Please Enter a Number");
sum += parseInt(number); //sum the numbers here
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
document.write('Average of scores : ' + sum / i);//use the sum of the numbers divide by the the numbers the user enters
}
show_prompt();
Tried to comment your old code with the mistakes:
function show_prompt() {
i = 0;
do {
//there is no need to declare number twice
//also you don't sum somewhere the numbers you get from the user
var number = prompt("Please Enter a Number");
var number = parseInt(number);
i++;
document.write("Number: " + number);
document.write("<br>");
}
while (i < 5);
}
show_prompt();
//number is out of scope of function show_prompt so is undefined
var avrg = number + number + number + number + number
//to get an avg you have to divide the sum by the number
document.write('Average of scores : ' + avrg);
Notice your var number is scoped within show_prompt(), it is not visible outside of it.
You need to have your show_prompt function not loop, and return the number, and have another function that calls show_prompt multiple times, takes the returns and calculate the average.. Also, your code is just calculating the sum, not the average
I'm not going to show you the exact code, but here's the idea
calc_average:
var sum=0;
loop 5 times:
sum = sum + show_prompt();
average = sum/5;
show_prompt:
var number = prompt('blah blah');
return number
I didn't think this was possible until console.log(); shown me that whats happening is impossible.
I can't understand how this is possible it's like those variables are being modified before code execution finishes.
I got this JavaScript code with debugging in it.
It's wrapped in this.
$('#buyAmountInput').keyup(function () {
var buyAmount = parseFloat($(this).val());
var totalPrice = 0;
var max = $(this).attr("max");
var min = $(this).attr("min");
if (buyAmount != $(this).val()) {
if (isNaN(buyAmount)) {
buyAmount = 1;
$(this).val('');
} else {
$(this).val(buyAmount);
}
} else {
if (buyAmount > max) {
buyAmount = max;
$(this).val(buyAmount);
} else if (buyAmount < min) {
buyAmount = min;
//$(this).val(buyAmount);
}
}
totalPrice = buyAmount * unitPrice;
//lots of code trimmed off here.
largessAmount = Math.round(buyAmount * largessRule.rebate) / 100;
////
console.log("Buy amount " + buyAmount + " LargessRebate " + largessRule.rebate);
console.log("Total Price " + totalPrice);
console.log("Largess Amount " + largessAmount);
console.log("New rate " + Number(totalPrice / (buyAmount + largessAmount)).moneyFormat());
console.log("No .moneyFormat() New rate " + Number(totalPrice / (buyAmount + largessAmount)));
console.log("( " + totalPrice + " / ( " + buyAmount + " + " + largessAmount + " ))");
////
$('#unitPrice').html(Number(totalPrice / (buyAmount + largessAmount)).moneyFormat());
});
Debug looks like this
Buy amount 5000 LargessRebate 20
Total Price 4250
Largess Amount 1000
New rate 0.71
No .moneyFormat() New rate 0.7083333333333334
( 4250 / (5000 + 1000))
function fastKeyListener content_script.js:208
Buy amount 5000 LargessRebate 20
Total Price 4250
Largess Amount 1000
New rate 0.00 //<- What happened here
No .moneyFormat() New rate 0.00008499830003399932 //<- What happened here
( 4250 / (5000 + 1000)) //<- Third line executed this will give good rate..
Even if the variables are global and this code is in a keypress up jQuery callback function.
The variables are printed before they are executed by console.log() and they are correct but the answer is dead wrong.
Here is the moneyFormat() which I don't think could be the problem could it?
var effective_bit = -2;
Number.prototype.moneyFormat = function () {
var num = this;
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * Math.pow(10, -effective_bit) + 0.50000000001);
cents = num % Math.pow(10, -effective_bit);
num = Math.floor(num / Math.pow(10, -effective_bit)).toString();
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 (effective_bit < 0) {
if (cents < 10 && effective_bit == '-2') cents = "0" + cents;
money = (((sign) ? '' : '-') + num + '.' + cents);
} else {
money = (((sign) ? '' : '-') + num);
}
return money;
};
I didn't post the whole code as it's very large, but you can see it live here
Just put into the Unit to buy of 4999, then scroll to 5000 it's all good.. try putting like 5001 or 50000 it will reset it to 5000 and give wrong answer in the process.
EDIT:
could of simplified the question to why does the console.log() functions evaluate incorrect answer if the same equation generated with the same variables just 1 line after in execution after gives correct answer, even on calculator.
Like some quantum going on here, bear with me there is nothing I could have done from 1 line to another line during that code-execution no breakpoints were set nothing plus those callbacks are functions generated in their own sandbox I believe so they are like ajax threads all working to complete sooner or later they all work separately from each other, so nothing working together here to mess it up. What you think could possibly happen here? some temporarily corruption or something?
This occurs sometimes when doing claulations using string variables.
Try converting the buyAmount and any variable that came from HTML to number before any calculation.
You can use the Number() function or parseFloat().
http://jsfiddle.net/rcdmk/63qas2kw/1/
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;
}
I am having trouble with a simple JavaScript calculation. My document is supposed to add $1.50 to an order if it is $25 or less, or add 10% of the order if it is more then $25. The exact problem is:
Many companies normally charge a shipping and handling charge for purchases. Create a Web page that allows a user to enter a purchase price into a text box and includes a JavaScript function that calculates shipping and handling. Add functionality to the script that adds a minimum shipping and handling charge of $1.50 for any purchase that is less than or equal to $25.00. For any orders over $25.00, add 10% to the total purchase price for shipping and handling, but do not include the $1.50 minimum shipping and handling charge. The formula for calculating a percentage is price * percent / 100. For example, the formula for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which results in a shipping and handling charge of $5.00. After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box.
This is my code:
var price = window.prompt("What is the purchase price?", 0);
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price){
if (price <= 25){
return 1.5;
}
else{
return price * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
When testing I enter a number in the prompt box, and instead of calculating as if I entered a number it calculates as if I entered a string. i.e. i enter 19 and it gives me 191.5 or I enter 26 and it gives me 262.6
Using parseFloat will help you:
var price = parseFloat(window.prompt("What is the purchase price?", 0))
var shipping = parseFloat(calculateShipping(price));
var total = price +shipping;
function calculateShipping(price){
if (price <= 25){
return 1.5;
}
else{
return price * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
See it working at: http://jsfiddle.net/e8U6W/
Also, a little-known put more performant way of doing this would be simply to -0:
var price =window.prompt("What is the purchase price?", 0) - 0;
(See: Is Subtracting Zero some sort of JavaScript performance trick?)
Be sure to comment this, though as its not as obvious to those reading your code as parseFloat
you can easily convert a string to a number
http://www.javascripter.net/faq/convert2.htm
basically JS provides parseInt and parseFloat methods...
Actually, you need to cast your text results into float values using parseFloat()
http://www.w3schools.com/jsref/jsref_parseFloat.asp
See my answer to the s/o question "Javascript adding two numbers incorrectly".
A bit of redundant multiplication, but your problem is that the numbers that are being inputted are treated as strings, not numbers. You have to convert them to floating point numbers:
var price = parseFloat(window.prompt("What is the purchase price?", 0));
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price)
{
if (price <= 25)
{
return 1.5;
} else {
return price / 10
}
}
window.alert("Your total is $" + total + ".");
var price = parseFloat(window.prompt("What is the purchase price?", 0));
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price){
var num = new Number(price);
if (num <= 25){
return 1.5;
} else{
return num * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
This should do it for you.