while loop not working in javascript [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm having a bit of trouble getting this code to work. I think it has something to do with the while loop. Also I'm new to JavaScript so, if you any suggestions on ways to improve the syntax or make my code more efficient it would be greatly appreciated.
how the code should work.
The user enters a cost of an item and then the amount of
money given. The program will figure out the change and the number of quarters, dimes, nickels, pennies needed for the change.
what happens when run
the two prompt boxes pop up and than I get a alert warning..
"A script on this page may be busy, or it may have stopped responding. You can stop the script now, open the script in the debugger, or let the script continue."
https://jsfiddle.net/krighty78/g44ejnbw/1/
/* The user enters a cost of an item and then the amount of
money given. The program will figure out the change and the number of quarters, dimes, nickels, pennies needed for the change.*/
var cost = prompt('please enter total cost of the item without tax');
cost = parseFloat(cost);
var moneyGiven = prompt('please enter the amount of money given');
moneyGiven = parseFloat(moneyGiven);
var tax = 0.15;
tax = (cost * tax);
var quarter = 0;
var dime = 0;
var nickel = 0;
var penny = 0;
var q = 0.25;
var d = 0.10;
var n = 0.05;
var p = 0.01;
var change = (moneyGiven - (cost + tax));
console.log(change);
while (change > 0) {
if (change >= q) {
change - q;
quarter++;
} else if (change >= d) {
change - d;
dime++;
} else if (change >= n) {
change - n;
nickel++;
} else if (change >= p) {
change - p;
penny++;
}
}; //while loop
console.log(quarter);
console.log(dime);
console.log(nickel);
console.log(penny);

The while loop is OK, the problem is in the statements
change - q;
change - d;
change - n;
change - p;
You are not updating the value of change. Change these to:
change = change - q;
change = change - d;
change = change - n;
change = change - p;

Related

Please help to translate code Pascal to JS? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
I have task: On a sheet of paper, a rectangle is drawn along the grid lines. After that, the number of grid nodes located inside, but not on the border of the rectangles, and the number of single grid segments inside the rectangle were counted. Write a program that uses this data to determine the size of a rectangle.
I have this code in Pascal:
var
K,N,i,j:integer;
begin
readln(K,N);
for i:=1 to trunc(sqrt(K)) do
if K mod i = 0 then
begin
if i*(K div i+1)+(K div i)*(i+1)=N then writeln(i+1,' ',K div i+1);
end;
end.
And this my code in JavaScript:
const a = [1000, 2065]
function Sum(K, N) {
for (i = 1; i < Math.trunc(Math.sqrt(K)); i++) {
if (K % i === 0 && i * (Math.floor(K / (i) + 1) + Math.floor(K / i) * (i + 1)) === N) {
break;
}
}
console.log(i + 1, Math.floor(K / (i)) + 1)
}
Sum(a[0], a[1]);
Can you help why my answers in JavaScript are wrong?
Not exactely sure what you're trying to achieve but this javascript code produces the same output (26, 41) as your pascal version does:
See onlinegdb.com!
const K = 1000, N = 2065;
for (let i=1; i<Math.trunc(Math.sqrt(K)); i++)
if (K % i === 0)
if (i*(K / i+1)+(K / i)*(i+1) === N)
console.log(i+1, K / i+1);
I think you have messed something up with the brackets in Math.floor or something similar.

Creating IF statement inside math.Random function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to create code that if we generate number between 20 and 120 and the generated number is >= than 100 then we want to reduce by 20. I dont want to create multiple random numbers..Can someone help ??
my basic math.rand function -
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
the code i tried to make
randomNumber(20,120);
if(randomNumber >= 100){
return randomNumber - 20;
}
message.reply(randomNumber);
In messages it display function randomNumber(min, max) { etc...
Store the result of the randomNumber function in a variable like this:
let number = randomNumber(20,120);
if(number >= 100){
number -= 20;
}
message.reply(number);
In JavaScript, you add () to run a function. Without those parentheses, you are just returning the code itself. When you state if(randomNumber >= 100), you aren't comparing the value that the function returns, rather the function itself.
When you call randomNumber(20,120) it returns a number, but you don’t put that number in any variable, so it just gets lost. And then you return randomNumber, which is a function, that’s why it prints out the content of the function.
To avoid that, create a variable containing the random number, like so:
let x = randomNumber(20,120);
if(x >= 100){
x -= 20;
}
message.reply(x);
Just save the result of your function in a variable and then check if that variable is >= 100 and if it is reduce it by 20 using a simple ternary operator.
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
number = randomNumber(20,120);
number = (number < 100) ? number : number -20;
console.log(number);

Calculate Ratios in JS like Humble Bundle

Do you know the sliders that you have on humblebundle.com when selecting where you want the money to go? Well when you adjust any one ratio it will automatically adjust the rest.
So say you're paying $20 no matter what but you want to adjust your tip to HB from $2 to $5, the ratios that were on the other stuff should automatically lowered to match but I have no idea what I'm doing.
This is as close as I get mathematically:
var settip = 50;
var tip = 5;
var devs = 75;
var donation = 20;
tip = settip;
var newAvail = 100 - tip;
var rCalc = 100 - (devs + donation);
devs = ((devs + rCalc) * newAvail) * .01;
donation = ((donation + rCalc) * newAvail) * .01;
console.log("New Ratio Calculation: " + rCalc);
console.log("New available space: " + newAvail);
console.log(tip);
console.log(devs);
console.log(donation);
The console logs are just so I can try and put it together in my head where things are going wrong. The numbers are also whole numbers first: 50 instead of .5 because Javascript is not accurate and I don't want to do the fix code every time, I'd rather figure out how to make the code work first and then think about optimizing.
So if anyone could guide me on a method or where I am going wrong here, then that'd be great. Thanks.
Tip is tip to the bundle maker.
Devs is tip to the devs.
Donation is tip to the donation box.
Each number is the ratio. Settip is the new ratio, I should be able to change any one value and have it automatically change all others but I can't even figure out how to do the first part so I couldn't begin to try for the second part of making it actually functional.
I think this problem is not as easy as it might seem if you want to cover different edge cases. Here I assume that you distribute money so you need following properties:
Each amount must be whole integer in cents
Sum of all amounts must be equal to the total sum
The simplest way to deal with it in JS is to make all calculations using whole numbers (e.g. sum in cents instead of dollars) and format them in more human-readable way on UI. Still even with this simplification it requires some non-trivial code:
function updateRates(rates, newValue, index) {
var i, len = rates.length;
var sum = 0;
for (i = 0; i < len; i++)
sum += rates[i];
var oldValue = rates[index];
var newRest = sum - newValue;
var curRest = sum - rates[index];
rates[index] = newValue;
var remainders = new Array(len);
var fraction, value, subsum = 0;
for (i = 0; i < len; i++) {
if (i === index) continue;
// special case, all other sliders were at 0 - split value equally
if (curRest === 0) {
fraction = 1.0 / (len - 1)
}
else {
fraction = rates[i] / curRest
}
value = newRest * fraction;
rates[i] = Math.floor(value); // always round down and then distribute rest according to the Largest remainder method
subsum += rates[i];
remainders[i] = {
index: i,
value: value - rates[i]
};
}
// sort remainders and distribute rest (fractions) accordingly
remainders.sort(function (a, b) {
var av = a.value;
var bv = b.value;
if (av === bv)
return 0;
if (av < bv)
return 1;
else
return -1;
});
for (i = 0; subsum < newRest; i++) {
rates[remainders[i].index] += 1;
subsum += 1;
}
return rates;
}
Some non-trivial tests:
1. updateRates([85,10,5], 82, 0) => [82, 12, 6]
2. updateRates([85,10,5], 83, 0) => [83, 11, 6]
3. updateRates([85,10,5], 84, 0) => [84, 11, 5]
4. updateRates([100,0,0], 95, 0) => [95, 2, 3]
5. updateRates([4,3,3,1], 0, 0) => [0, 5, 5, 1]
Pay attention to the example #5. If one used some naive rounding, sum will not be preserved. Effectively you need to distribute +4 in proportion 3:3:1. It means you should add +12/7, +12/7 and +4/7. Since 12/7 = 1 5/7, according to standard mathematical rules all three should be rounded up resulting in +2, +2, +1 but we only got +4 cents to distribute. To fix this issue the largest remainder method is used to distribute fractional cents among categories. Simply speaking the idea is that we first distribute only whole number of cents (i.e. always round down), calculate how many cents are actually left and then distribute them one by one. The biggest possible drawback of this method is that some rates that started with equal values might have different values after update. On the other hand this can't be avoided as example #4 shows: you can't split 5 cents equally between two categories.
To restate what I think you want: the three variables tip, devs and donation should always sum to 100. When one variable is updated, the other two should be updated to compensate. The automatic updates should keep the same ratios to each other (for example, if donation is double devs, and tips is updated, then the updated donation value should still be double the devs value).
If I've got that right, then this should work for you:
var tips = 5;
var devs = 20;
var donation = 75;
var setTips = function(newValue) {
tips = newValue;
var sum = devs + donation;
var devShare = devs / sum; // the share devs gets between devs and donation
var donationShare = 1 - devShare; // or could calculate as donation / sum
devs = (100 - tips) * devShare; // the remaining times it's share ratio
donation = (100 - tips) * donationShare; // the remaining times it's share ratio
};
// test it out
setTips(50);
console.log(tips, devs, donation);

javascript program without using math. pow, find power of any number using for loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I need to know the code built in for the syntax math.pow(x,y). Actually I used the syntax to find exponent of any number... e.g.
var e = Math.pow(-3, 3); yields -27 but couldn't find out the program behind this... Help me please
If you know what power means..
multiplying the number x n times where x is base and n is exponent.
So you just have to repeat the same thing over and over - and that's why loops are for:
var sum = 1; //note that it's not zero!
for (int i=0;i<n;i++) { //loops n times
sum = sum * x; //on each loop multiplies sum by base number
}
Did you mean alternative for Math.pow? Here is one way with simple loop.
function pow(base,power) {
var p = 1;
for (var i=0; i<power; i++) {
p *= base;
}
return p;
}
You can also use recursion to solve this kind of challenge. Beware that recursion has the disadvantage of increasing space complexity as compared to a for-loop.
function pow(base, power) {
if (power === 1) return base * power
return base * pow(base, power - 1)
}
This is a better way to calculate power of a number with recursion:
function power(base, exp) {
if(exp === 0){
return 1;
}
return base * power(base, exp - 1);
}
You can try this:
function pow(n, e) {
let num = n;
for (let i = 1; i < e; i++) {
num *= n;
}
return num;
}
console.log(pow(-3, 3));
It will give you the required result.

How to achieve this Pricing Calculator [duplicate]

This question already has answers here:
Price Calculator based on Quantity [closed]
(4 answers)
Closed 8 years ago.
I am trying to create a simple script to add to a html website.
I need it to calculate the price based on the quantity the user inputs.
For example, a value of 1-1000 will be multiplied by 1.50 and displayed, 1001-5000 multiplied by 1.20 and displayed, 5001-10000 multiplied by 1 and displayed and any number above that would display an error message like "Must be below 10000".
The result is to display in a text field so the user can click submit.
I've been trying to do this in js with no success. If this can be done in any other language please let me know. I'm still learning.
function calc(val) {
if (val < 1 || val > 10000) {
alert("Value must be a positive number under 10,000")
return 0;
}
if (val < 1001) return val*1.5;
if (val < 5001) return val*1.2;
return val;
}
This can be done trough almost every language available for web. Calculating is the most easy thing. For example, in PHP:
$output = $input - 5; // -5
$output = $input + 5; // +5
$output = $input++; // +1
$output = $input * 5; // x5
Javascript plus example:
var input = 5;
var plus = 6;
var output = input+plus;
Javascript min example:
var input = 5;
var plus = 6;
var output = input-plus;

Categories