简体   繁体   English

使用Java / javascript的十进制值的数学余数商数程序

[英]Math remainder quotient program for decimal values using Java/javascript

Hi I am trying to write a program using Javascript/Java to get the quotient (with decimal values) and remainder as shown in the below attachment. 嗨,我正在尝试使用Javascript / Java编写一个程序来获取商(带小数值)和余数,如下面的附件所示。 I used regular remainder operator (%) but not getting the actual remainder as shown below. 我使用了常规余数运算符(%)但没有得到实际的余数,如下所示。 Can someone please help me how to implement this. 有人可以帮我解决如何实现这个问题。 在此输入图像描述

Non-zero remainder: 非零余数:

在此输入图像描述

In Javascript I wrote: 在Javascript中我写道:

<script>
 var a = 17.0;
 var b = 5;
 var x = a % b;
</script>

Where as In Java when I wrote 我在写作时在Java中的位置

import java.math.*;
public class CalculateRemainder {
public static void main(String[] args) {
  float divider, remainder;
  int dividend;

  divider = 17.0f;
  dividend = 5;

  remainder = divider%(dividend);

  String str = "The remainder is " + remainder;
  System.out.println( str);
  }
 }

I am getting Remainder as "2.0" instead of "0" (as shown in the image). 我将Remainder设为“2.0”而不是“0”(如图所示)。 Same is the case with JavaScript. JavaScript的情况也是如此。

If you want the remainder after some precision then use this: 如果你想要一些精度后的余数,那么使用这个:

 function remainder(dividend, divisor, precision = 4) { var result = (dividend / divisor).toString(); var dot = result.indexOf('.'); if(dot == -1) return 0; // it was a perfect division (9 / 3 for example) var remainder = "0." + result.substr(dot + precision); // get the part after the precision return Math.round(remainder * divisor); // multiply it by the divisor and round the result } console.log(remainder(9.1, 3, 3)); 

Note: The result could be different for different precisions. 注意:对于不同的精度,结果可能不同。

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

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