简体   繁体   English

Javascript计算总和,除非它小于零

[英]Javascript calculate sum unless it is less than zero

Just a quick question, can this sum be written in one short line: 只是一个简单的问题,这笔钱可以写成一个简短的行:

  a = (b / c) * 100;
  if (a < 0) a = 0;

Apart from the obvious way which is equally long: 除了明显的方式同样长:

 if ((b / c) * 100) > 0) a = (b / c) * 100; else a = 0;

EDIT: And the ternary version of this is no different, I didn't think I needed to mention. 编辑:这三元版本没有什么不同,我认为我不需要提及。

Maybe there isn't a short, neat and clever way to write this but I was just hoping there was since it always seems unnecessary to have that extra line underneath. 也许没有一个简短,巧妙和聪明的方式来写这个,但我只是希望有,因为它总是似乎没有必要在下面有额外的线。

您可以将Math.max与零一起使用。

a = Math.max(b * 100 / c, 0);

您可以使用三元运算符:

a = ((b / c) * 100) >= 0 ? ((b / c) * 100) : 0;

You may use a ternary expression: 您可以使用三元表达式:

a = (b / c) * 100 > 0 ? (b / c) * 100 : 0;

This assigns a to the quantity (b / c) * 100 , unless that quantity be less than or equal to zero, in which case it just assigns zero to a . 这将a指定给数量(b / c) * 100 ,除非该数量小于或等于零,在这种情况下它只为a指定零。

// I do not think that *100 is necessary in your test
a = (b / c) < 0 ? 0 : (b / c) * 100;

这是我能想到的唯一方法

a = (b / c * 100) >= 0 ? (b / c * 100) : 0;

Actually the result is negative if one of b or c is negative (but not both). 实际上,如果b或c中的一个是负数(但不是两个),结果是否定的。 So a bit longer but actually with only necessary calculations and more comparisons: 所以有点长,但实际上只有必要的计算和更多的比较:

b < 0 ? c > 0 ? a = 0 : a = b * 100  / c : c < 0 ? a = b * 100 : a = 0;

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

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