简体   繁体   English

简单的JavaScript数学问题

[英]Simple javascript math problem

How do I express this in javascript? 如何用javascript表达?

9H squared plus 3H all over 2 times L 9H平方加3H超过2倍L

I'm working on something like: 我正在做类似的事情:

function calculator (height, len) {
var H = height, L = len;
total = (((9 * H)*(9 * H)) + 3*H)/2)*L;
return total;
}

calculator(15, 7);

I don't care if it's terse or not, but I'm not sure the best way to handle math in javascript. 我不在乎它是否简洁,但是我不确定在javascript中处理数学的最佳方法。

thank you. 谢谢。

Squaring a number x can be represented as Math.pow(x, 2) . 将数字x平方可以表示为Math.pow(x, 2) Also, "all over 2 times L" would mean / (2 * L) at the end rather than the way you have it, if you do really mean: 此外,“ 2倍于L的总和”将在末尾表示/ (2 * L) ,而不是您的计算方式,如果您的确表示:

  whatever
-----------
    2L

You are also missing the var keyword before total , which would declare it as a local variable. 您还缺少total之前的var关键字,该关键字会将其声明为局部变量。

Horner's method is a nice way of expressing polynomials: Horner方法是表达多项式的一种好方法:

function calc (height, length) {
     return ((9*height + 3)*height)/(2*length);
}

http://en.wikipedia.org/wiki/Horner_scheme http://en.wikipedia.org/wiki/Horner_scheme

Looks almost fine to me. 在我看来几乎没问题。 What's the problem you're having? 你有什么问题?

The only thing I see wrong is a missing var before total, thus making it global. 我唯一看错的是总计之前缺少var ,因此使其成为全局变量。 Change your code to: 将您的代码更改为:

function calculator (height, len) {
    var H = height,
        L = len, // <-- subtle change: replace ; with ,
        total = (((9 * H)*(9 * H)) + 3*H)/2)*L;
    return total;
}

Of course, you could also factor out the 9: 当然,您也可以排除9:

total = ((81*H*H + 3*H)/2)*L;

And if you want to get even fancier, then factor out the common 3*H as well: 如果您想变得更高级,那么也请考虑常见的3*H

total = (3*H*(27*H + 1)/2)*L;

But I'm not sure what else you're looking for here. 但是我不确定您还在这里寻找什么。

In "9H squared" it's only the H that is squared, so 在“ 9H平方”中,只有H平方,所以

function calculator (height, len) {
    var H = height, L = len;
    var total = (9*H*H + 3*H)/(2*L);
    return total;
}

+1 to Andrew Cooper +1到安德鲁·库珀

(9*H)*(9*H) = 81*H^2, which i dont believe you intend (9 * H)*(9 * H)= 81 * H ^ 2,我不相信您打算

9*H*H = 9H^2 is how you intend that term 9 * H * H = 9H ^ 2是您打算使用的术语

(9*H*H + 3*H) / (2*L) (9 * H * H + 3 * H)/(2 * L)
or factor 或因素
(3*H)(3*H+1)/(2*L) (3 * H)(3 * H + 1)/(2 * L)

Which is equal to the sum of 1 + 2 + .. + 3H all divided by L (if H is an intger) 等于1 + 2 + .. + 3H的总和除以L(如果H是整数)
This last part probably doesn't do anything for you, but I like the identity =P 最后一部分可能对您没有任何帮助,但我喜欢标识= P

You might go about it like so... 你可能会这样...

function calculator (height, len) {
  var h = height, l = len;
  var total = ( 9 * Math.pow(h, 2) + 3*h ) / (2*l);
  return total;
}

Don't forget making a variable with out var prepended will make it global :) 不要忘记在变量前加上var来使它成为全局的:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM