Home > Article > Backend Development > How to write php to calculate the sum of even numbers
PHP calculates the sum of even numbers
1. Define the Show class and define the method sum
2. Method Pass in two numbers, find the sum of all even numbers between the two numbers inside the method body, return the calculated result to
3, and output the returned result
Note: the two numbers passed in, the smaller number passed in first and the larger number passed in second, cannot be equal.
The code is as follows:
<?php header('content-type:text/html;charset=utf8'); class show{ public $one; public $two; function sum($one,$two){ $num=0; if($one>$two){ for ($i=$two; $i <= $one; $i++) { if($i%2==0){ $num+=$i; } } }else if($two>$one){ for ($i=$one; $i <= $two ; $i++) { if($i%2==0){ $num+=$i; } } }else{ return "错误,两个数不能相等";//如果两个数相等 } return "两数之间的所有偶数和为".$num; } } //实例化类 $show=new show(); //进行调用 echo $show->sum(20,30);//输入两个数值
Recommended tutorial: PHP video tutorial
The above is the detailed content of How to write php to calculate the sum of even numbers. For more information, please follow other related articles on the PHP Chinese website!