當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Math cos()用法及代碼示例


java.lang.Math.cos()返回角度的三角餘弦。如果參數為NaN或無窮大,則返回的結果為NaN。返回的值將在[-1,1]範圍內。

用法:

public static double cos(double angle)
Parameters:
The function has one mandatory parameter angle which is in radians. 

返回值:
該函數返回角度的三角餘弦。


範例1:展示java.lang.Math.cos()方法的用法。

// Java program to demonstrate working 
// of java.lang.Math.cos() method 
import java.lang.Math; 
  
class Gfg { 
  
    // driver code 
    public static void main(String args[]) 
    { 
        double a = 30; 
          
        // converting values to radians 
        double b = Math.toRadians(a); 
  
        System.out.println(Math.cos(b)); 
  
        a = 45; 
          
        // converting values to radians 
        b = Math.toRadians(a); 
  
        System.out.println(Math.cos(b)); 
  
        a = 60; 
          
        // converting values to radians 
        b = Math.toRadians(a); 
  
        System.out.println(Math.cos(b)); 
  
        a = 0; 
          
        // converting values to radians 
        b = Math.toRadians(a); 
  
        System.out.println(Math.cos(b)); 
    } 
}
輸出:
0.8660254037844387
0.7071067811865476
0.5000000000000001
1.0

範例2:在參數為NAN或無窮大時顯示java.lang.Math.cos()方法的用法方式。

// Java program to demonstrate working 
// of java.lang.Math.cos() method infinity case 
import java.lang.Math; // importing java.lang package 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        double positiveInfinity =  
               Double.POSITIVE_INFINITY; 
        double negativeInfinity =  
               Double.NEGATIVE_INFINITY; 
        double nan = Double.NaN; 
        double result; 
  
        // Here argument is negative infinity,  
        // output will be NaN 
        result = Math.cos(negativeInfinity); 
        System.out.println(result); 
  
        // Here argument is positive infinity,  
        // output will also be NaN 
        result = Math.cos(positiveInfinity); 
        System.out.println(result); 
  
        // Here argument is NaN, output will be NaN 
        result = Math.cos(nan); 
        System.out.println(result); 
    } 
}
輸出:
NaN
NaN
NaN


相關用法


注:本文由純淨天空篩選整理自ChetnaAgarwal大神的英文原創作品 Java Math cos() method with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。