This is my page:
http://dl.dropboxusercontent.com/s/3kc058darzus1uu/pythagoras_questions.html
And it's supposed to be a revision site for some students I'm tutoring, but I'm having some trouble getting a number to round to 2 dp and I'm not sure why. I've written on lines 99 to 107:
function answers() {
c = Math.sqrt(a*a+b*b)
console.log(c)
Math.round(c*100)/100
console.log(c)
var el = document.getElementById("c")
el.innerHTML="$"+c+"$"
MathJax.Hub.Queue(["Typeset", MathJax.Hub, el])
}
but for some reason it skips the Math.round() function. Here's a sample output from the console:
46.32493928760188
46.32493928760188
I just don't understand why it isn't rounding, what am I doing wrong? Strangely typing
Math.round(c*100)/100
directly into the console gives: 46.32.
Screenshot:
You have to assign the result (returned value) of Math.round(c * 100) / 100 to the variable c again.
And always use a semicolon to separate your JavaScript statements so that you won't have an error when two statements get on the same line (f.e. when you minify the js).
function answers() {
var c = Math.sqrt(a * a + b * b);
c = Math.round(c * 100) / 100;
var el = document.getElementById("c");
el.innerHTML = "$" + c + "$";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, el]);
}
You need:
c = Math.round(c*100)/100;
As it is, your function doesn't update c, nor write its result to any variable.
You need to assign the result of Math.round to a variable, e.g.
c = Math.round(c*100)/100;
mkay why make multiple set's
when u can just
function answers() {
c = Math.round(Math.sqrt(a*a+b*b)*100)/100
console.log(c)
var el = document.getElementById("c")
el.innerHTML="$"+c+"$"
MathJax.Hub.Queue(["Typeset", MathJax.Hub, el])
}
Edit:
another alternative
if the number is already a float is the .toFixed() option
function answers() {
c = Math.sqrt(a*a+b*b).toFixed(2)
console.log(c)
var el = document.getElementById("c")
el.innerHTML="$"+c+"$"
MathJax.Hub.Queue(["Typeset", MathJax.Hub, el])
}
Related
I'm trying to write a function (GetPositiveInteger) that generates a random integer between variables a and b. if a > b, it's supposed to switch the values of the two so that b=>a before generating the Number.
I don't know if I'm misunderstanding the question or what because I can't figure out where I'm meant to be converting a and b to integers and my program keeps just returning NaN. here's my code maybe someone could take a look at it?
function GetRandomInteger(a, b, c) {
a = Number(a), b = Number(b);
if (a > b) {
var a = 2,
b = 1,
c = a;
a = b;
b = c;
} else {
var x = parseInt(Math.random() * b) + a;
}
return x;
}
let x;
console.log(Number(GetRandomInteger(x)));
When a > b, you're setting them to specific numbers before swapping them, instead of swapping the original values.
The code that generates the random number shouldn't be in else, because you won't run that after swapping a and b. It should just be after the if.
You don't need the c parameter. Use a temporary variable declared inside the function when swapping.
Use Math.floor() to convert a floating point number to an integer. parseInt() is for parsing strings (it will work in this case because it first converts the float to a string, but it's better to use the more specific function).
You need to call the function with two arguments. In the example below I just hard-coded them, but you can use your function that asks the user for numbers. Just use it twice to set two variables.
function GetRandomInteger(a, b) {
a = Number(a), b = Number(b);
if (a > b) {
let temp = a;
a = b;
b = temp;
}
var x = Math.floor(Math.random() * b) + a;
return x;
}
console.log(GetRandomInteger(1, 10));
console.log(GetRandomInteger(15, 3));
i am so newbie in programming, what i want is create a file which able automatically count triangel around (actually this is pythagoras problem).
i had tried to code with simple programming (the result is written below), and use function in javascript.
i use simple html file to call the javascript file, but the result is always wrong.
function fungsiKllSegitiga1(a,b) {
var c = Math.SQRT(a * a + b * b);
var kll=a+b+c;
return c.sqrt;
}
function fungsiKllSegitiga2(a,b) {
var c = (a * a + b * b)^(0.5);
var kll=a+b+c;
return c.sqrt;
}
i want variable c to count pythagoras, but i can't do it properly. any suggestion?
Try This:
function fungsiKllSegitiga1(a,b) {
var c = Math.SQRT(a * a + b * b);
return c;
}
fungsiKllSegitiga1(tmp, tmp)
tmp means temporary, change it to the numbers you want.
This question already has answers here:
Addition is not working in JavaScript
(7 answers)
Closed 9 years ago.
i'm having some trouble with the parseInt function or + operand. I want to take in two numbers, multiply one by a third number and add them together. Instead of adding the numbers it appends one number to another.
<script language = 'JavaScript'>
function calculate_total()
{
var a = 0;
var b = 0;
var t = 0;
parseInt(a = prompt('Pay 1'), 10);
//Input of 10
if(isNaN(a))
{
alert('Error A');
}
//No Error
parseInt(b = prompt('Pay 2'), 10);
//input of 12
if(isNaN(b))
{
alert('Error B');
}
//No Error
parseInt(t = (a * 20 + b), 10);
if(isNaN(t))
{
alert('Error T');
}
else
{
alert('Total Pay: ' + t);
//expected answer 212
//Actual Answer 20012
}
//No Error
}
calculate_total();
</script>
parseInt(a = prompt('Pay 1'), 10);
...
parseInt(b = prompt('Pay 2'), 10);
...
parseInt(t = (a * 20 + b), 10);
Here a, b and t, all have got string data only and when it is converted to an int, its discarded immediately. So, fix them like this
a = parseInt(prompt('Pay 1'), 10);
...
b = parseInt(prompt('Pay 2'), 10);
...
t = a * 20 + b;
According to ECMA Script's specifications for Additive operation,
7 If Type(lprim) is String or Type(rprim) is String, then Return the
String that is the result of concatenating ToString(lprim) followed by
ToString(rprim)
So when you use a string and number with + operator, result will be concatenation of both the operands.
According to ECMA Script's specifications for Multiplicative operation,
Let left be the result of evaluating MultiplicativeExpression.
Let leftValue be GetValue(left).
Let right be the result of evaluating UnaryExpression.
Let rightValue be GetValue(right).
Let leftNum be ToNumber(leftValue).
Let rightNum be ToNumber(rightValue).
* operator basically converts both the operands to numbers. So, the result will be proper even if both the operands are numbers in strings.
You can confirm the above mentioned things with this
var a = "100", b = "12";
console.log(a * 20); // Prints 2000, both operands are converted to numbers
console.log(a * 20 + b); // Prints 200012, as b is string, both are concatenated
I'm not a Javascript expert by any means, but you seem to be ignoring the result of parseInt, instead storing just the result of prompt() in your a, b and t variables. I'd expect this:
parseInt(a = prompt('Pay 1'), 10);
to be:
a = parseInt(prompt('Pay 1'), 10);
(And the same for the other prompts.)
At that point, the variables' values will be the numbers rather than the strings, so + should add them appropriately.
You parsing result which is already wrong due to appending as string:
try updating following statements:
a = parseInt(prompt('Pay 1'), 10);
b = parseInt(prompt('Pay 2'), 10);
t = a * 20 + b; // no need to parse as a and b already integers
parseInt() returns an integer value. And you dony need parseInt(string, 10), for parseInt decimal system used by defaults.
a = parseInt(prompt('Pay 1'));
b = parseInt(prompt('Pay 2'));
t = a * 20 + b;
try
a = parseInt(prompt('pay 1'),10);
etc. for b and t.
Now you declare a as prompt('pay 1') and not as the int value returned by parseInt.
I've fixed the code for you:
<script language = 'JavaScript'>
function calculate_total()
{
var a = 0;
var b = 0;
var t = 0;
a = parseInt(prompt('Pay 1'), 10);
//Input of 10
if(isNaN(a))
{
alert('Error A');
}
//No Error
b = parseInt(prompt('Pay 2'), 10);
//input of 12
if(isNaN(b))
{
alert('Error B');
}
//No Error
t = parseInt(a * 20 + b, 10);
if(isNaN(t))
{
alert('Error T');
}
else
{
alert('Total Pay: ' + t);
//expected answer 212
//Actual Answer 20012
}
//No Error
}
calculate_total();
</script>
Hello I am trying to do a simple calculation of three values: a + b * c but getting wrong total. If a is 10 and b is 10 it would be 20 multiplied by c which is 2.4. I should get 48 as total. Currently getting 2424.
function compute() {
var a = $('#a').val();
var b = $('#b').val();
var c = $('#c').val();
var total = (a + b) * c;
$('#total').val(total);
}
$('#a, #b, #c').change(compute);
Basic maths : multiplication have precedence over addition.
So in your code, a is additionned to the result of b*c .
Use :
var total = (a + b) * c;
a + b * c is being evaluated as a + (b * c)
What you need is (a + b) * c
Precedence: Brackets > Division > Multiplication > Addition > Subtraction
In your question, you stated that you get 1024. Getting 1024 is impossible. You should get 34. (Check your calculation elsewhere)
a + (b * c) = 10 + (10 * 2.4) = 34
If you want to add a to b BEFORE multiplying, you'll need to use parentheses.
That's because the multiplication oprator has higher precedence than addition.
(a + b) * c
try after parsing the values like:
var total = (parseFloat(a) + parseFloat(b)) * parseFloat(c);
$(document).ready(function() {
function compute() {
var a = $('#a').val();
var b = $('#b').val();
var c = $('#c').val();
var total = (parseInt(a,10) + parseInt(b,10)) * parseFloat(c); alert(total);
$('#total').val(total);
}
$('#a, #b, #c').change(compute);
});
Check DEMO
Your variables are strings. Use parseFloat function.
"10" + "10"*"2.4" = "10"+ 24 = "1024"
How can i prevent to javascript interpret my numeric vars from string vars?
var a = 100;
var b = -10
var c = a + b // 10-10 (string)
lets say i allways want
var c = a + b = 100+(-10) = 90 (number)
In your example c will always be 90, however;
var a = 100;
var b = "-10";
var c = a + b // "100-10" (string)
to prevent this convert the string to an integer;
var c = a + parseInt(b, 10);
or with a unary+
var c = a + +b;
Your code example...
var a = 100;
var b = -10
var c = a + b // 90 (number)
...won't do that unless one of the operands is a String. In your example, both are Number.
If you do have numbers inside of Strings, you can use parseInt() (don't forget to pass the radix of 10 if working in decimal) or possibly just prefix the String with + to coerce it to Number.
Your code works fine. See here.
JavaScript will always do the latter, as long as both of the variables you are adding are numbers.
The most concise way is prepending a + if you aren't certain whether the variables are numbers or strings:
var a = "100";
var b = "-10";
var c = +a + +b; // 90
This works since +"123" === 123 etc.