2014-09-25 69 views
2

我一直在试图解决Project Euler问题1,我觉得我错过了一些基本的东西。你能帮我解决我的错误吗?将整数推入数组的问题

我想这第一:

<?php 
/* 
** Project Euler Problem 1 
** If we list all the natural numbers below 10 that are multiples of 3 or 5, 
** we get 3, 5, 6 and 9. The sum of these multiples is 23. 
** Find the sum of all the multiples of 3 or 5 below 1000. 
*/ 
$numberOne = 3; 
$numberTwo = 5; 
$endingIndex = 1000; 
$multiplesOfNumbers = array(); 

for ($index = 1; $index <= $endingIndex; $index++) { 
    if ($index % $numberOne == 0 && $index % $numberTwo == 0) { 
     $multipleOfNumbers[] = $index; 
    } 
} 
echo $multiplesOfNumbers; 
?> 

输出:

阵列

所以我试图用array_push做到这一点,而不是像这样:

<?php 
/* 
** Project Euler Problem 1 
** If we list all the natural numbers below 10 that are multiples of 3 or 5, 
** we get 3, 5, 6 and 9. The sum of these multiples is 23. 
** Find the sum of all the multiples of 3 or 5 below 1000. 
*/ 
$numberOne = 3; 
$numberTwo = 5; 
$endingIndex = 1000; 
$multiplesOfNumbers = array(); 

for ($index = 1; $index <= $endingIndex; $index++) { 
    if ($index % $numberOne == 0 && $index % $numberTwo == 0) { 
     // $multipleOfNumbers[] = $index; 
     array_push($multiplesOfNumbers, $index); 
    } 
} 
echo $multiplesOfNumbers; 
?> 

输出是一样的。我错过了什么?

+0

字符串上下文中的数组将简单地为'Array'。 – 2014-09-25 20:50:57

回答

6

试试这个方法:

print_r($multiplesOfNumbers); 
+2

另请参见:echo array_sum($ multiplesOfNumbers); – 2014-09-25 20:42:58

2

echo将不打印数组元素。使用print_r而不是

0

您必须遍历数组以获取数组的值(使用foreach)或使用类似var_dump()或print_r()的方法来回显数组。