strictfp

strictfp, 即 strict float point (精確浮點)。

基本介紹

  • 中文名:精確浮點
  • 外文名:strict float point
  • 用途:類、接口或方法
  • 注意:符合IEEE-754規範。
簡介,示例,

簡介

Strictfp —— Java 關鍵字
strictfp 關鍵字可套用於類、接口或方法。使用 strictfp 關鍵字聲明一個方法時,該方法中所有的float和double表達式都嚴格遵守FP-strict的限制,符合IEEE-754規範。當對一個類或接口使用 strictfp 關鍵字時,該類中的所有代碼,包括嵌套類型中的初始設定值和代碼,都將嚴格地進行計算。嚴格約束意味著所有表達式的結果都必須是 IEEE 754 算法對運算元預期的結果,以單精度和雙精度格式表示。
如果你想讓你的浮點運算更加精確,而且不會因為不同的硬體平台所執行的結果不一致的話,可以用關鍵字strictfp.

示例

示例 1
下面的示例演示了一個使用 strictfp 修飾符聲明的類。
// Example of precision control with strictfp
public strictfp class MyClass
{
public MyClass(){}
public static void main(String[] args)
{
float aFloat = 0.6710339f;
double aDouble = 0.04150553411984792d;
double sum = aFloat + aDouble;
float quotient = (float)(aFloat / aDouble);
System.out.println("float: " + aFloat);
System.out.println("double: " + aDouble);
System.out.println("sum: " + sum);
System.out.println("quotient: " + quotient);
}
}
示例輸出
float: 0.6710339
double: 0.04150553411984792
sum: 0.71253945297742238
quotient: 16.1673355
示例 2
下面的示例演示了一個使用 strictfp 修飾符聲明的方法。
// Example of precision control with strictfp:
public class MyClass2
{
public float aFloat;
public double aDouble;
public MyClass2(){}
public strictfp double add(float a, double b)
{
return (a + b);
}
public static void main(String[] args)
{
MyClass2 myClass2 = new MyClass2();
myClass2.aFloat = 0.6710339f;
myClass2.aDouble = 0.04150553411984792d;
double sum = myClass2.add(myClass2.aFloat, myClass2.aDouble);
System.out.println("float: " + myClass2.aFloat);
System.out.println("double: " + myClass2.aDouble);
System.out.println("sum: " + sum);
}
}
示例輸出
float: 0.6710339
double: 0.04150553411984792
sum: 0.71253945297742238

相關詞條

熱門詞條

聯絡我們