我試圖創建一個具有以下結構的陣列:For循環分配錯誤的數組索引
[10] => Array
(
[10] => test key
...
[100] => test key
)
[20] => Array
(
[10] => test key
...
[100] => test key
)
[30] => Array
(
[10] => test key
...
[100] => test key
)
...
這是我爲了用它來創建這種結構的循環:
$array = array();
for ($x = 0.1; $x <= 1; $x+=0.1) {
$index = $x*100;
for ($z = 10; $z <= 100; $z+=10) {
$array[(int)$index][$z] = 'test key';
}
}
不幸,一旦它應該達到90和100索引,我收到的輸出就是這樣的:
[80] => Array
(
[10] => test key
...
[100] => test key
)
[89] => Array
(
[10] => test key
...
[100] => test key
)
[99] => Array
(
[10] => test key
...
[100] => test key
)
爲什麼它計算的索引是89和99?它們不應該分別是90和100嗎?
*編輯 我使用浮點數,因爲這是我們用來進行一些計算的百分比度量。我知道我也可以增加10個增量,但這需要我最終再次除以100才能獲得浮點數
[閱讀,學習和了解(https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems );那麼明白當從float到int的投射時,PHP會下降 –
但是爲什麼你仍然使用浮動? –
爲什麼在10年代這樣一個複雜的遞增方式 – nogad