Home>Article>Backend Development> PHP Algorithm Exercise 12: Get the absolute value between n and 51 and return the value as required

PHP Algorithm Exercise 12: Get the absolute value between n and 51 and return the value as required

藏色散人
藏色散人 Original
2021-08-31 09:21:47 1897browse

In the previous article "PHP Algorithm Exercise 11: Check whether two given integers are within the specified range", I introduced how to check whether two given integers are within the specified range. Friends in need can learn about it~

This article will continue to bring you a series of PHP algorithm exercises. [Recommended:PHP algorithm exercise series summary (continuously updated~)]

First of all, let me describe the problem to be solved in this article: "How to write a PHP program to obtain n and 51 The absolute value between. If n is greater than 51, three times the absolute value is returned."

Related introduction: The absolute value refers to the distance from the corresponding point of a number on the number axis to the origin, represented by "| |". |b-a| or |a-b| represents the distance between the point representing a and the point representing b on the number axis.

Let’s go directly to the code:

 $x) { return ($n - $x)*3; } return $x - $n; } echo test(53)."
"; echo test(30)."
"; echo test(51)."
";

The execution results are as follows:

6 21 0

It’s very simple to implement!

Here we mainly need to master the use of if conditional statements, and then implement the execution process according to the requirements. For example, in this example, if n is greater than 51, it is required to return three times the absolute value, that is, the "($n - $x)*3;" formula must be executed; otherwise, the absolute value of the two numbers is directly returned.

Related introduction:

In PHP, we can use the following conditional statements:

  • if statement: If the specified condition is true, Then execute the code;

  • if...else statement: If the condition is true, the code is executed; if the condition is false, the other end of the code is executed;

  • if...elseif....else statement: execute different code blocks based on two or more conditions;

  • switch statement: select among multiple code blocks One to execute.

Finally, I would like to recommend the latest and most comprehensive "PHP Video Tutorial"~ Come and learn!

The above is the detailed content of PHP Algorithm Exercise 12: Get the absolute value between n and 51 and return the value as required. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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