PHP Algorithm Exercise 1: Calculate the sum of two numbers and three times their sum

藏色散人
Release: 2023-04-10 14:00:02
Original
2548 people have browsed it

When you step into the door of PHP, learning will never end. Only when the foundation is strong can you flourish and achieve fruitful results. So today I will start the PHP arithmetic series of articles. I hope everyone will practice together regardless of the difficulty. Bar.

The question for the arithmetic exercise in this article is "Write a PHP program to calculate the sum of two given integer values ​​and, if the two values ​​are the same, return three times their sum".

The following is the method I gave:

PHP code:

<?php
function test($x, $y)
{
    return $x == $y ? ($x + $y)*3 : $x + $y;
}
echo test(1, 2)."<br>";
echo test(3, 2)."<br>";
echo test(2, 2)."<br>";
Copy after login

The output calculation result is:

PHP Algorithm Exercise 1: Calculate the sum of two numbers and three times their sum

In the above code, the core code part is "$x == $y? ($x $y)*3: $x $y;", the meaning of this code That is to first determine whether $x and $y are equal. If they are not equal, execute "$x $y". If they are equal, execute "($x $y)*3".

In this example, the first pair of parameters we give are 1 and 2, which are different values, so the returned result is their sum, which is 3;

The second The parameters for the pair are 3 and 2. Similarly, the returned sum is 5;

The parameters given for the third pair are 2 and 2, which are two identical values, so the returned result is three times their sum. times, that is, 3*(2 2)=12.

Here you need to master an important operator, the ternary operator "?:".

The syntax format is "(expr1) ? (expr2) : (expr3)"

When expr1 is evaluated to TRUE, the value is expr2, and expr1 is evaluated. The value when FALSE is expr3.

Note:

Since PHP 5.3, the middle part of the ternary operator can be omitted. The expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE and expr3 otherwise.

For a detailed introduction to PHP operators, you can read the "PHP Operators" chapter in the manual.

Finally, I would like to recommend to you the latest free course on our platform "Entering the World of PHP from 0"~ Come and learn!

The above is the detailed content of PHP Algorithm Exercise 1: Calculate the sum of two numbers and three times their sum. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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