Home > Backend Development > PHP Tutorial > Find the sum of all even numbers between two numbers in php

Find the sum of all even numbers between two numbers in php

WBOY
Release: 2016-07-29 08:49:52
Original
3184 people have browsed it

Define the Show class
Define the method sum in the class
Pass in two numbers in the method
Find the sum of all even numbers between the two numbers inside the method body
Return the calculated result
Output the returned result
The output form is as follows
The sum of all even numbers between the two numbers is: 30

Note: the smaller number is passed in first and the larger number is passed in second. The two numbers cannot be equal.

The code is as follows:

<?php 
header(&#39;content-type:text/html;charset=utf8&#39;);

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);//输入两个数值
Copy after login

The above introduces how to find the sum of all even numbers between two numbers in PHP, including the content between PHP and PHP. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template