javascript simple bmi calculator doesnt work as intended [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 8 years ago.
Improve this question
var userweight = prompt ("What is your weight?");
var userheight = prompt ("What is your height in meter?");
var bmi = function (userweight,userheight){
return userweight/(userheight*userheight);
};
var bmi= function(calc){
if(calc<=18.4){
return("you are thin");
}
else if (18.5<=calc<=24.9){
return("you are normal");
}
else if (25.0<=calc<=29.9){
return("you are fat");
}
else if (calc>=30.0){
return("you have obesity");
}
};
bmi(userweight,userheight);
I tried to make a bmi calculator. It calculates your bmi . But it had problems in if/else part. It only shows "You are normal" no matter what bmi it is

At the first, you override the first bmi-formula function assignment with your if/else statements.
You should rename one of these functions:
var userweight = prompt("What is your weight?");
var userheight = prompt("What is your height in meter?");
var formula = function(userweight,userheight){
return userweight / (userheight * userheight);
};
var bmi = function(userweight, userheight){
var calc = formula(userweight, userheight);
if (calc <= 18.4) {
return "you are thin";
}
if (calc >= 18.5 && calc <= 24.9) {
return "you are normal";
}
if (calc >= 25.0 && calc <= 29.9) {
return "you are fat";
}
if (calc >= 30.0) {
return "you have obesity";
}
};
alert( bmi(userweight, userheight) );
The second thing is, that your condition to return the "normal"-part (18.5<=calc<=24.9) is falsey, you could do it like this: calc >= 18.5 && calc <= 24.9. (The same for the "fat"-part)
The last note, as you can see, I've removed the else-keywords since we return a value after if, it doesn't matter what then comes.

You declare the bmi function expression
var bmi = function (userweight,userheight){
return userweight/(userheight*userheight);
};
but the subsequent declaration later on overwrites it completely. So when you call
bmi(userweight, userheight)
Javascript takes the passed in userweight and assigns it to calc. The BMI isn't calculated at all, your first function is never called.
userheight is never used; JavaScript doesn't care if you pass in too many arguments.
Give your functions different names e.g. renaming your first function to calculateBMI and the second one to adviseOnBMI (or whatever you fancy) and rerun it.
console.log is your friend when debugging - use it to output to the Developer Console in your browser of choice.

Related

JavasScript Add half a percent to a number any amount of times I choose

Hi I need a block of code for some math that I'm trying to work out. The code I'm looking for will be able to add half a percent (0.005) to a number and return the result back to me. I need the code to take two separate inputs, the first is the start number, and the second is how many times I want the loop to execute. An example would be if I started with 7000 the code should output ~7321.37 (if possible let it stop after 2 decimal points). Thank you for the help in advance!
Code example of what I'm trying to do:
function growth(initialValue, timesOfExecution)` {
let answer;
let execute;
while (execute > 0) {
answer = initialValue + initialValue(0.05)
execute--
}
return answer;
}
console.log(growth(7000, 9))
Here you go:
function growth(initialValue, timesOfExecution) {
for (let i = 0; i < timesOfExecution; i++) {
initialValue = initialValue + (initialValue * 0.005)
}
return initialValue.toFixed(2);
}
console.log(growth(7000, 9))

javascript while loop problem,break doesn't stop the loop [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 3 years ago.
Improve this question
I built a simple number guessing game with javascript.
After the computer guess the correct answer it should break the loop.
What I am wondering is that even though I break the loop at Line 18
It still execute the code on Line 20(console.log(text)).
The funny thing is that after the break. Only console.log() get executed,L21 & L22 don't do anything,which they are supposed to be that way.
Can't really figure out why. I hope I make the question clear!
Executes last console.log() in repl example
But doesn't in the below snippet (the exact same code)..
let answer = Math.floor(Math.random() * 100) + 1
// start coding
console.log('Answer is ' + answer)
let max = 100
let min = 0
let guess = Math.floor((max + min) / 2)
let i = 1
while (true){
let text = `#${i}: computer guess ${guess}.`
if (guess > answer){
text += 'TOO BIG!'
max = guess
} else if (guess < answer){
text += 'TOO Small!'
min = guess
} else{
text += 'win!'
break
}
console.log(text)
guess = Math.floor((max + min) / 2)
i++
}
My guess is that because the REPL tool tries to display a return value for the code you run, it's using the last value before the code exits, which is text += "win!". So it's not actually executing your console.log(text), it just looks like it is.
For example, if you change your code to the following, the REPL tool spits out a number (the value of i before the postfix). Because it's the last value it saw before the while loop exited.
REPL example showing a different "return" value, logging as expected
let answer = Math.floor(Math.random() * 100) + 1
// start coding
console.log('Answer is ' + answer)
let max = 100
let min = 0
let guess = Math.floor((max + min) / 2)
let i = 1
while (guess !== answer){
let text = `#${i}: computer guess ${guess}.`
if (guess > answer){
text += 'TOO BIG!'
max = guess
} else if (guess < answer){
text += 'TOO Small!'
min = guess
}
console.log(text)
guess = Math.floor((max + min) / 2)
i++
}
// console.log(`#${i}: computer guess ${guess}. Win!`);
This is not normal JS behavior, and should be taken with a grain of salt when reading "return" values in the REPL tool.Hope this helps!

How to write and call functions in javascript with for loops?

I am working on writing code for a course and need to figure out why the code output is not executing properly. I am very new to coding, this is a beginner assignment so all help and explanations are greatly appreciated.
The output should look like this:
Output:
How many times to repeat? 2
Stats Solver execution 1 ====================
give a number 10.10203
give a number 20
give a number 30
give a number 40
give a number 50
sum: 150.10203
average: 30.020406
max: 50
min: 10.10203
ratio: 4.94
Stats Solver execution 2 ====================
give a number 3.21
give a number 2.1
give a number 1
give a number 5.4321
give a number 4.321
sum: 16.0631
average: 3.21262
max: 5.4321
min: 1
ratio: 5.43
done ====================
Here is the code:
"use strict";
function myMain() {
var num = Number(prompt("give a number of times to repeat, must be 0 or greater"));
var count = num;
for (var a=0; a<=num; a++) {count++;}
alert("Stats Solver execution " + num + " ===================");
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
}
function wall(){
var num1 = Number(prompt("provide a number"));
var num2 = Number(prompt("provide a second number"));
var num3 = Number(prompt("provide a third number"));
var num4 = Number(prompt("provide a fourth number"));
var num5 = Number(prompt("provide a fifth number"));
var sum = (num1+num2+num3+num4+num5);
alert("sum: " + sum);
var avg = (sum/5);
alert("average: " + avg);
var max = (Math.max(num1,num2,num3,num4,num5));
alert("max: " + max);
var min = (Math.min(num1,num2,num3,num4,num5));
alert("min: " + min);
var ratio = (max/min);
alert("ratio: " + Math.floor(ratio*100)/100);
}
myMain();
Well you really aren't very far off at all. Actually your solution has all the code you need just some of it is in the wrong place. I would have posted this as a comment but as this is a new work account I can't actually post comments so here is a full solution with the explanations.
Your wall function, while annoying with all the alerts is actually correct and doesn't need any adjustments. With that said you might want to play with parseInt and parseFloat to make sure you are getting valid numbers but I am assuming that is outside of the scope of the assignment.
Now on to your main function.
var num = Number(prompt("give a number of times to repeat, must be 0 or greater"));
This is ok and will prompt the user for a number, once again you might want to test that you got a valid number using the aforementioned links.
var count = num;
for (var a=0; a<=num; a++) {count++;}
alert("Stats Solver execution " + num + " ===================");
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
This is where things start to fall apart a bit and where i think you are having problems. So I will break this down line for line and explain what each line is doing and you can compare that to what you think its doing.
var count = num;
Nothing crazy here, you are just creating another variable to hold the value in the num variable. Slightly redundant but not really a big deal.
for (var a=0; a<=num; a++) {count++;}
This is the line that appears to have given you the most confusion. This is the actual loop but inside the body of the loop { .... } nothing is being done except 1 is being added to count (count++). If I am understanding the assignment correctly, inside this loop is where you need to call your wall function after alerting the 'Stats Solver execution .....' stuff. All you need to do is move your function call inside this loop.
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
This part is clearly you a little lost and just trying things to get it to work, don't worry even after 12+ years of development i still write code like this ;). You really don't need this as the actual call to wall() will work fine for you.
I am bored and am waiting on work so for the sake of being a complete answer here is an example of how your code should look. Please don't just hand this in rather try and actually understand the difference between what i wrote and what you did because these are some very basic concepts that if you gloss over will make your life much harder down the road. Always feel free to ask, thats how people learn.
function myMain(){
// get the number of repetitions from the user and cast as a number
var num = Number(prompt('Please enter the number of times to repeat'));
// loop from 0 to the number the user provided - 1 hence the <
for (var i = 0; i < num; i++){
// alert the iteration of the loop, you will notice i add 1 to num when we alert it; this is because it starts at 0 so the first time it displays it would show 'Stats Solver execution 0 ======' instead of 'Stats Solver execution 1 ======'
alert('Stats Solver execution ' + (num + 1) + ' ===============');
// call your wall function
wall();
// go back to the top of the loop
}
// alert that we are done.
alert('done===============')
}
// your wall function goes here
// call your myMain function to kick everything off
myMain();
Just for fun you might want to look at console.log instead of alert to not make it such an annoying process with all the popups.
If i missed anything or you are confused about anything don't hesitate to ask and i'll do my best to answer.

Javascript beginner - Can anyone tell me why my button doesn't work?

jsfiddle is here --> http://jsfiddle.net/diabetesjones/015k1tjn/5/
here's an example of one that does work:
http://jsfiddle.net/Ahopefulmachine/dkhj8o38/
Regarding the second jsfiddle (not mine), I don't quite get why his works without using document.getElementById on the button.
i feel like my problem is in the click function itself of :
document.getElementById('mainButton').onclick = function () {
thanks :)
working now: http://jsfiddle.net/doniyor/015k1tjn/9/
you had document.getElementByID which should be document.getElementById
AND
you didnot convert strings to int like numberOne = parseInt(numberOne, 10); where 10 is radix for decimal.
you had question == ADD which should be question == 'ADD'
There are three things wrong with your code:
It's getElementById not getElementByID (case-sensitive).
You didn't convert the strings you get from the input to numbers. You can do this easily by adding a + in front of the document.getElementById('number1').value;
You were doing comparisons against variables, not strings. Ex question == ADD instead of question == 'ADD'
See corrected jsFiddle example
document.getElementById('mainButton').onclick = function () {
//Getting values of inputs and saving them to variables
var numberOne = +document.getElementById('number1').value;
var numberTwo = +document.getElementById('number2').value;
//Setting values of the equations
var addition = (numberOne + numberTwo);
var subtraction = (numberOne - numberTwo);
var multiplication = (numberOne * numberTwo);
var division = (numberOne / numberTwo);
//Prompting user for their desired equation
var question = prompt("Do you wish to ADD, SUBTRACT, MULTIPLY, or DIVIDE?").toUpperCase();
//If statement to show the proper equation based on the user's prior prompt
if (question == 'ADD') {
alert('I added the shit out of those numbers for you - turns out it is ' + addition);
} else if (question == 'SUBTRACT') {
alert('Did some of this, some of that, some minusing - your answer is ' + subtraction);
} else if (question == 'MULTIPLY') {
alert('Yeah, I multipled the numbers, big whoop, wanna fight abouddit? the answers over there --> ' + multiplication);
} else if (question == 'DIVIDE') {
alert('This ones my favorite, I love a good division - ' + division);
};
};

JavaScript window.alert not working

I recently began learning JavaScript and decided to create a program to factor quadratic functions. The program itself is longer, and takes three users inputs (secondnum,firstnum,thirdnum) representing a,b,c in the standard form ax^2+bx+c. The program functions normally until this block of code.
function discriminant(secondnum,firstnum,thirdnum) {
var disc = Math.sqrt(Math.power(secondnum,2)-(4*firstnum*thirdnum));
return disc;
}
ans1 = ((-1*secondnum) + disc)/(2*firstnum);
ans2 = ((-1*secondnum) - disc)/(2*firstnum);
window.alert(ans1);
window.alert(ans2);
My intention of this code is creating a function which solves for the discriminant, then uses the discriminant in the quadratic formula. I believe there is something incorrect about the discriminant function. Is this the proper way to use user input in the function?
I hope this question is not too specific.
Also if it matters here is an example of how I collect user input for (secondnum)
var secondnum = prompt ("enter b");
while (isNaN(secondnum) || secondnum == "") {
var secondnum = prompt ("enter a different b");
}
Thank you in advance.
I am not 100% sure on the math, but syntactically I think you are trying to do something like this
function discriminant(secondnum,firstnum,thirdnum) {
var disc = Math.sqrt(Math.pow(secondnum,2)-(4*firstnum*thirdnum));
return disc;
}
ans1 = ((-1*secondnum) + discriminant(firstnum, secondnum, thirdnum))/(2*firstnum);
ans2 = ((-1*secondnum) - discriminant(firstnum, secondnum, thirdnum))/(2*firstnum);
window.alert(ans1);
window.alert(ans2);
which will at least get your alert boxes working provided firstnum, secondnum and thirdnum are declared before this block executes

Categories

Resources