Javascript Trapezoid area calculation with user input, incorrect result - javascript

I am trying to make a javascript program that calculates the area of a trapezoid. So far below is my js code:
var lol=prompt("Please enter which 2d polygon you would like this awesome calculator to calculate.")
if(lol==="trapezoid"){
var tr1=prompt("Enter the top base.")
var tr2=prompt("Enter the bottom base.")
var tr3=prompt("Now enter the height.")
confirm((tr1+tr2)*(tr3)/2)
}
But when I put 4,5,6 in my calculator, it spits out 135 instead of 27.
Why?

You can use parseInt to set the values as integers.
var lol=prompt("Please enter which 2d polygon you would like this awesome calculator to calculate.")
if(lol==="trapezoid"){
var tr1=Number(prompt("Enter the top base."))
var tr2=Number(prompt("Enter the bottom base."))
var tr3=Number(prompt("Now enter the height."))
confirm((tr1+tr2)*(tr3)/2)
}
Here's a JSFiddle with Benjamine's Number point
http://jsfiddle.net/cXWnk/

The values you are getting back from the prompt are strings and, as Ryan P says, "1" + "1" = "11".
What you need to do is cast the strings to integers before using their values in the calculation.
You can do this with the Number() function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
So, your code might be:
confirm((Number(tr1) + Number(tr2)) *(Number(tr3))/2)
or, using the unary plus shorthand:
confirm((+tr1 + +tr2)*(+tr3)/2)

Related

I need help determining the difference between my code that I believe produces the same result as another, but won't be accepted

I am stuck on how my code will not be accepted by freeCodeCamp's auto-grader. The objective was to create a function without any parameters that will generate a random number using Math.random(). Then we would have to multiply the randomly generated number by 10. After multiplying the randomly generated by 10, I would have to use Math.floor() to round it up or down.
Link to challenge: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-with-javascript
These are the objectives given to me, quoted directly from freeCodeCamp's challenge:
1.) The result of randomWholeNum should be a whole number.
2.) You should use Math.random to generate a random number.
3.) You should have multiplied the result of Math.random by 10 to make it a number that is between zero and nine.
4.) You should use Math.floor to remove the decimal part of the number.
Here is my code:
function randomWholeNum() {
var x = Math.random();
var z = x * 10;
var y = Math.floor(z);
return y;
}
As you can see, I used multiple variables to complete this task. x would generate the random number, z would store the random number multiplied by 10, y would round z, resulting in all objectives passed. However, when running the code, all objectives were ticked except for Number 3. I don't understand what went wrong, and after looking at the answer for the challenge, which is:
function randomWholeNum() {
// Only change code below this line.
return Math.floor(Math.random() * 10);
}
I don't understand why the code I wrote doesn't produce the same result of freeCodeCamp's own.

Modifying hoverformat in plotly

How would I make it so that when hovering over a plotly graph, the displayed value in the hoverbox can be divided by 1000 and have a "K" appended to it?
For instance, when hovering over "$10,000,000" in a plotly graph, what could be done so that "$10,000K" is displayed in the box?
Specifically, can anything be done with the "hoverformat" property? It currently looks like this:
hoverformat: ",.0f"
I'm aware that this prints a float with 0 decimal places...but how would I specify the displayed value to be divided by 1000 and then have a "K" appended?
Thanks.
You might consider using numeral for that purpose. Numeral is a library used to format numbers and you can find it here:
http://numeraljs.com/
You then could do something like
const number = 10000;
const formattedNumber = numeral(10000).format('$ 0.00 a');

Calculate speed from velocity vector using box2d GetLinearVelocity();

I need to find the speed of an object in a game. The game is made in HTML5 with jquery and jquery.box2d.
For this I can use these methods:
GetLinearVelocity().x;
GetLinearVelocity().y;
I'm then trying to calculate the speed from this piece of code, but get some values that doesn't make sense when I console.log it. This is my code:
var heroVelX = game.currentHero.GetLinearVelocity().x;
var heroVelY = game.currentHero.GetLinearVelocity().y;
var speed = Math.sqrt(heroVelX^2 + heroVelY^2);
console.log(speed);
Some of the values in console.log are numbers, but most of them are NaN (Not-A-Number), which confuses me? Can someone help me solve this?
The goal I want to achieve, is to see when the speed(of object .currenHero) drop below a certain value, so I can excute a new state in the game.
Your problem is that you're using the wrong operator (Bitwise XOR) for doing square - see here.
What you need to do is:
var speed = Math.sqrt(Math.pow(heroVelX, 2) + Math.pow(heroVelY, 2));
The only time the square root function should return NaN is when the value being square rooted is negative. A way to go about testing if this is the issue would be to try squaring the values in a different line of code before square rooting them.
heroVelX = (heroVelX) * (heroVelX)
Another way to potentially shine some light on the problem would be to add log statements printing out the values of the velocities and the velocities squared before square rooting.

trig functions with imaginary numbers in javascript

I am trying to write some code in javascript to calculate trig functions, inverse trig functions, and hyperbolic trig functions with imaginary numbers. I have the sin, cos, sinh, and cosh working well. However, I am having some trouble getting my solutions for others to match the only verification that I can find at this site.
For example, below is the code for asin(x+yi). I am using the formula located here along with the definitions for modulus and argument found there as well. It has no errors, but doesn't match the results from the site I cited. What am I doing wrong?
asin(z)=-i*ln(iz+sqrt(1-z^2))
var id1=SquareComplex (window[id].Solution_real, window[id].Solution_imag);
var real=1-window[id1].Solution_real;
var imag=window[id1].Solution_imag;
var id2=SquareRoot(real, imag);
imag=window[id].Solution_real+window[id2].Solution_imag;
real=-window[id].Solution_imag+window[id2].Solution_real;
var modulus=Math.sqrt(real^2+imag^2);
var argument=Math.atan2(imag,real);
var Solution_imag=-Math.log(modulus);
var Solution_real=argument;
This code is intended to work in several steps. The first line calls a function that squares the complex number z. The second and third lines subtract the result from the number 1. The fourth line calls a function to take the square root of the complex number. The fifth and sixth lines add the results of the previous actions to the result of multiplying the complex number by i. The remaining lines get the modulus and argument of those results, take the natural logarithm, and multiply it by a negative i.
Your first three lines are:
var id1=SquareComplex (window[id].Solution_real, window[id].Solution_imag);
var real=1-window[id1].Solution_real;
var imag=window[id1].Solution_imag;
assuming that id is your initial z then this is not calculating the real and imaginary parts of 1-z^2 as I believe it is indtended to. The reason being that the imaginary part isn't being subtracted.
Try it with
var imag = -window[id1].Solution_imag;
and see if that helps. I can't guarantee there aren't any more errors in it but I'd suggest just going through and being really careful about making sure each line does what it should.
You may be interested in math.js, which comes with support for complex numbers for all functions including trigonometry:
var value = math.complex(2, 3);
var ans = math.asin(value);
Or using the expression parser:
var ans = math.eval('asin(2 + 3i)');

Multiply variable to one decimal place

My employer wishes for a textbox to convert feet to metres to one decimal place, however, I am unfamiliar with Javascript and only know the bare basics for HTML purposes. My current code converts it correctly, but it is not to one decimal place.. Any suggestions?
Code:
<script type="text/javascript">
<!--
function validate() {
var ft = document.getElementById('LengthFt');
var res=0.3048*ft.value;
var mtrs = document.getElementById('LengthMtrs');
mtrs.value = res;
}
//-->
</script>
It looks like you've done the conversion. After that, all you need to do is format the number properly.
The toFixed method can be used to format to a fixed number of decimal places.
Replacing
mtrs.value = res;
with
mtrs.value = res.toFixed(1);
should leave the right number in the LengthMtrs input accurate to the closest decimeter.

Categories