PHP Increment by Half

杀马特。学长 韩版系。学妹 提交于 2020-01-01 09:02:29

问题


I have a quick question, which is probably easy to answer. I've goolged around, but not sure if I am searching correctly or what. Anyway, using PHP, how can I increment by halves?

For example, I know I can use the following loop:

<?php 
for ($i=1; $i<21; $i++) {
    print($i);
}

And it will print 1 - 20.

But, how can I get it to output something like the following:

1
1.5
2
2.5
etc...

Sorry for my ignorance on this, I'm just not sure how to go about it. Thanks!


回答1:


Change $i++ to $i += 0.5. Also, to print each number on its own line you need to use \n (or <br> if you're outputting HTML to a browser).

for ($i = 1; $i < 21; $i += 0.5) {
    print($i . "\n");
}

The above code will print 20.5 because it's less than 21. If you want to print a maximum of 20, change the loop condition to check $i <= 20 instead:

for ($i = 1; $i <= 20; $i += 0.5) {
    print($i . "\n");
}



回答2:


Just one more solution to choose from.

foreach (range(1, 20, 0.5) as $i) {
  // Do something with $i
}



回答3:


Loop to double the amount (adjust upper and lower bounds appropriately) and divide by two in the output.

E.g.

for ($i=2; $i<41; $i++) print($i/2);

to output from 1 to 20 in increments of .5




回答4:


instead of $i++, use $i += .5




回答5:


Here's something that could work.

$i += round(exp(log(2)/2) * 2) / 2 - ENT_QUOTES + IMAGETYPE_JPEG;


来源:https://stackoverflow.com/questions/4822611/php-increment-by-half

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!