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


CoffeeScript Math sqrt()用法及代碼示例


描述

這個sqrt()方法接受一個數字並返回其平方根值。如果數字的值為負,則 sqrt 返回 NaN。

用法

下麵給出的是sqrt()JavaScript 的方法。我們可以在 CoffeeScript 代碼中使用相同的方法。

Math.sqrt ( x )

示例

下麵的例子演示了sqrt()CoffeeScript 中的方法。將此代碼保存在具有名稱的文件中math_sqrt.coffee

value = Math.sqrt 0.5
console.log "The square root of 0.5 is:" + value 

value = Math.sqrt 81
console.log "The square root of 81 is:" + value 

         
value = Math.sqrt 13
console.log "The square root of 13 is:" + value 
 
value = Math.sqrt -4
console.log "The square root of -4 is:" + value

打開command prompt並編譯 .coffee 文件,如下所示。

c:\> coffee -c math_sqrt.coffee

在編譯時,它會為您提供以下 JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var value;

  value = Math.sqrt(0.5);

  console.log("The square root of 0.5 is:" + value);

  value = Math.sqrt(81);

  console.log("The square root of 81 is:" + value);

  value = Math.sqrt(13);

  console.log("The square root of 13 is:" + value);

  value = Math.sqrt(-4);

  console.log("The square root of -4 is:" + value);
  
}).call(this);

現在,打開command prompt再次運行 CoffeeScript 文件,如下所示。

c:\> coffee math_sqrt.coffee

在執行時,CoffeeScript 文件產生以下輸出。

The square root of 0.5 is:0.7071067811865476
The square root of 81 is:9
The square root of 13 is:3.605551275463989
The square root of -4 is:NaN

相關用法


注:本文由純淨天空篩選整理自 CoffeeScript Math - sqrt()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。