PHP - Ds Vector::sum() 函式



PHP 的 Ds\Vector::sum() 函式用於檢索向量中所有值的總和。根據當前向量中存在的值,這些值可以是 floatint

在計算向量中所有值的總和時,陣列和物件被視為零。

語法

以下是 PHP Ds\Vector::sum() 函式的語法:

public Ds\Vector::sum(): int|float

引數

此函式不接受任何引數。

返回值

此函式返回向量中所有值的總和。

示例 1

以下是 PHP Ds\Vector::sum() 函式的基本示例:

<?php 
   $vector = new \Ds\Vector([2, 4, 6, 8]);
   echo "The original vector: \n"; 
   print_r($vector);
   echo "The sum of elements: ";
   #using sum() function   
   print_r($vector->sum()); 
?>

輸出

以上程式產生以下輸出:

The original vector:
Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
)
The sum of elements: 20

示例 2

以下是 PHP Ds\Vector::sum() 函式的另一個示例。我們使用此函式來檢索此 ([2.5, 5.4, 1.2, 3.6, 7.6, 4.3]) 向量所有元素的總和:

<?php 
   $vector = new \Ds\Vector([2.5, 5.4, 1.2, 3.6, 7.6, 4.3]); 
   echo("The original vector: \n"); 
   print_r($vector);
   echo("The sum of elements: "); 
   print_r($vector->sum());
?>

輸出

執行以上程式後,將顯示以下輸出:

The original vector:
Ds\Vector Object
(
    [0] => 2.5
    [1] => 5.4
    [2] => 1.2
    [3] => 3.6
    [4] => 7.6
    [5] => 4.3
)
The sum of elements: 24.6

示例 3

在下面的示例中,我們使用 sum() 函式來檢索包含 int 和 float 值的向量的所有元素的總和:

<?php 
   $vector = new \Ds\Vector([10, 5.4, 6.3, 12, 20.5, 5]); 
   echo("The original vector: \n"); 
   print_r($vector);
   echo("The sum of elements: "); 
   print_r($vector->sum()); 
?>

輸出

執行以上程式後,將顯示以下輸出:

The original vector:
Ds\Vector Object
(
    [0] => 10
    [1] => 5.4
    [2] => 6.3
    [3] => 12
    [4] => 20.5
    [5] => 5
)
The sum of elements: 59.2
php_function_reference.htm
廣告