简体   繁体   中英

How to use mathematical variables in php to solve an equation

I am currently unable to figure out how I would do the following in php.. eval? But how?

The main problem? I'm not sure how to use mathematical variables like "X" and "Y".

If someone could show me how to solve the following equation in php, it would be awesome!

There are 30 students in a class, and 4 more girls then there are guys.

x = boys
y = girls

x + 4 = y
x + y = 30
(Substitution)
x + (x + 4) = 30
2x + 4 = 30
2x = 26

x = 13

y = 17

Thanks!

Just to clarify, I have taken a look at eval, and I have not found any sufficient examples on how to use it in this manner - If I had, I would not've asked this question. If anyone can point me to examples which use mathematical variables like this - that's also appreciated, but the question that was flagged as "might being an answer to my question", has not answered my question sufficiently.

Neither do the php docs on eval.

There's no simple easy way to solve any given type of equation in PHP. You might also be looking for something more like MATLAB , as PHP wasn't exactly designed with this in mind.

You can write algorithms in any language to solve it, though. Here I've solved yours using randomness and brute force (probably the simplest and one of the least efficient methods):

<?php

while ($total != 30 || $girls != $boys + 4) {
    $girls = rand(0, 30);
    $boys = rand(0, 30);
    $total = $girls + $boys;
}

echo "There are {$girls} girls and {$boys} boys.";

In academic Computer Science, solutions to problems like these are called Algorithms , and graduates usually cite that course as their program's most important (along with Data Structures ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM