j2me中有没有sgn函数,J2ME中Math.round如何使用有?

programfish 2009-04-15 04:03:37
j2me中有没有sgn函数,J2ME中Math.round如何使用有?
...全文
202 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
nick12183371 2009-04-15
  • 打赏
  • 举报
回复
学习学习
JarodYv 2009-04-15
  • 打赏
  • 举报
回复
sgn函数返回表示数字符号的整数,J2ME中没有这个函数,但是实现起来很好实现

public static int sgn(int num){
if(num==0)
return 0;
return num>0?1:-1;
}


java.lang.Math类里有两个round()方法,它们的定义如下:

Java代码

public static int round(float a) {
//other code
}

public static long round(double a) {
//other code
}
它们的返回值都是整数,且都采用四舍五入法。运算规则如下:
  ①如果参数为正数,且小数点后第一位>=5,运算结果为参数的整数部分+1。

  ②如果参数为负数,且小数点后第一位>5,运算结果为参数的整数部分-1。

  ③如果参数为正数,且小数点后第一位<5;或者参数为负数,且小数点后第一位<=5,运算结果为参数的整数部分。
我们可以通过下面的例子来验证:


public class MathTest {
  public static void main(String[] args) {
     System.out.println("小数点后第一位=5");
     System.out.println("正数:Math.round(11.5)=" + Math.round(11.5));
     System.out.println("负数:Math.round(-11.5)=" + Math.round(-11.5));
     System.out.println();

     System.out.println("小数点后第一位<5");
     System.out.println("正数:Math.round(11.46)=" + Math.round(11.46));
     System.out.println("负数:Math.round(-11.46)=" + Math.round(-11.46));
     System.out.println();

     System.out.println("小数点后第一位>5");
    System.out.println("正数:Math.round(11.68)=" + Math.round(11.68));
     System.out.println("负数:Math.round(-11.68)=" + Math.round(-11.68));
  }
}

运行结果:

1. 小数点后第一位=5
2. 正数:Math.round(11.5)=12
3. 负数:Math.round(-11.5)=-11
4.
5. 小数点后第一位<5
6. 正数:Math.round(11.46)=11
7. 负数:Math.round(-11.46)=-11
8.
9. 小数点后第一位>5
10. 正数:Math.round(11.68)=12
11. 负数:Math.round(-11.68)=-12

根据上面例子的运行结果,我们还可以按照如下方式总结,或许更加容易记忆:

1. 参数的小数点后第一位<5,运算结果为参数整数部分。
2. 参数的小数点后第一位>5,运算结果为参数整数部分绝对值+1,符号(即正负)不变。
3. 参数的小数点后第一位=5,正数运算结果为整数部分+1,负数运算结果为整数部分。

但是上面的结论仍然不是很好记忆。我们来看看round()方法的内部实现会给我们带来什么启发?我们来看这两个方法内部的代码:

public static int round(float a) {
return (int)floor(a + 0.5f);
}

public static long round(double a) {
return (long)floor(a + 0.5d);
}


看来它们都是将参数值+0.5后交与floor()进行运算,然后取返回值。那么floor()方法的作用又是什么呢?它是取一个小于等于参数值的最大整数。比如经过floor()方法运算后,如果参数是10.2则返回10,13返回13,-20.82返回-21,-16返回-16等等。既然是这样,我们就可以用一句话来概括round()方法的运算效果了:

* Math类的round()方法的运算结果是一个<=(参数值+0.5)的最大整数。

13,100

社区成员

发帖
与我相关
我的任务
社区描述
Java J2ME
社区管理员
  • J2ME社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧