dart:math
dart:math 函式庫 (API 參考) 提供了常見的功能,例如正弦和餘弦、最大值和最小值,以及常數,例如 pi 和 e。 Math 函式庫中的大多數功能都實作為頂層函式。
若要在您的應用程式中使用此函式庫,請匯入 dart:math。
dart
import 'dart:math';
三角函數
#Math 函式庫提供了基本三角函數
dart
// Cosine
assert(cos(pi) == -1.0);
// Sine
var degrees = 30;
var radians = degrees * (pi / 180);
// radians is now 0.52359.
var sinOf30degrees = sin(radians);
// sin 30° = 0.5
assert((sinOf30degrees - 0.5).abs() < 0.01);
最大值與最小值
#Math 函式庫提供了 max()
和 min()
方法
dart
assert(max(1, 1000) == 1000);
assert(min(1, -1000) == -1000);
數學常數
#在 Math 函式庫中尋找您最愛的常數—pi、e 及更多
dart
// See the Math library for additional constants.
print(e); // 2.718281828459045
print(pi); // 3.141592653589793
print(sqrt2); // 1.4142135623730951
隨機數
#使用 Random 類別產生隨機數。您可以選擇性地為 Random 建構子提供種子。
dart
var random = Random();
random.nextDouble(); // Between 0.0 and 1.0: [0, 1)
random.nextInt(10); // Between 0 and 9.
您甚至可以產生隨機布林值
dart
var random = Random();
random.nextBool(); // true or false
更多資訊
#請參閱 Math API 參考 以取得完整的方法列表。另請參閱 num、 int 和 double 的 API 參考。
除非另有說明,否則本網站上的文件反映 Dart 3.7.1 版本。頁面最近更新於 2024-11-17。 檢視原始碼 或 回報問題。