Jump to content

For Loop Adds One More?


chaseman

Recommended Posts

I'm trying to automatically change a math equation so that the solution is an even number:

 

It is at first complicated but I'm progressing.

 

This is my first attempt at accomplishing what I'm trying to accomplish.

 

 if (($sol != round($sol)) && ($x1 < $x2)) {

/***********************************************************/
function round_up ($sol, $x1, $op, $x2) {

	for ($x1 = $x1; $sol < round($sol); $x1++) {

		switch ($op) {

		case '+' : $sol = $x1 + $x2; break;
		case '-' : $sol = $x1 - $x2; break;
		case '*' : $sol = $x1 * $x2; break;
		case '/' : $sol = $x1 / $x2; break;

		}	
	}

	return (array ($sol, $x1, $op, $x2));

}
/**********************************************************/

	$round_array = round_up($sol, $x1, $op, $x2);


echo "after for loop: $round_array[1] $round_array[2] $round_array[3] = and sol: $round_array[0] <br /><br />";

 }

 

If the solution of the equation is not a round number, and if the first number is smaller than the other, than increase the first number until the solution is a round number.

 

It is a very primitive solution, but I'm learning as I go and I'll try to make it more intelligent. But to my problem, the above script outputs following values:

 

first calc: 3 / 5 = ? 

first sol: 0.6 

after for loop: 6 / 5 = and sol: 1 

 

The script will increase the first number about 1 digit more, and that is exactly my problem, since that way the equation makes no sense.

 

The condition of the for loop is, increase $x1 till $sol is SHORTLY before the next rounded number, when it is has reached the next rounded number STOP.

 

Thus $x1 should be 5 in the above example, because 5/5 = 1.

 

IT seems that after $sol has reached the next round number, the for loop will go one more time over the variables, and THEN it will stop.

 

How can I solve this problem?

Link to comment
Share on other sites

You defintely need to take a different approach - that is going to be a headache.

 

But, your problem is the fact that you are using a for loop and increasing $x1 in the third parameter of that loop. From the manual

At the end of each iteration, expr3 is evaluated (executed). 

 

So, on the last iteration of the loop where the condition $sol < round($sol) is no longer true, the third expression ($x1++) is executed again - increasing the value one more than you intended. You should use a while() loop and increment $x1 in the loop. However, I think that code is pretty bad to start with.

 

function round_up ($sol, $x1, $op, $x2)
{
    while($sol < round($sol))
    {
        $x1++;
        switch ($op)
        {
            case '+' : $sol = $x1 + $x2; break;
            case '-' : $sol = $x1 - $x2; break;
            case '*' : $sol = $x1 * $x2; break;
            case '/' : $sol = $x1 / $x2; break;
        }
    }
    return (array ($sol, $x1, $op, $x2));
}

Link to comment
Share on other sites

Thanks a lot, that one worked great.

 

I didn't know that it will go till the 3rd expression, I thought it would stop at the condition, thanks for letting me know.

 

I realize the code is quite bad as it is, but I'm just experimenting around for now. Programming game type apps with PHP is much harder than programming websites. You definitely have to be able think around the corner.

 

EDIT:

 

When you say "different approach" do you have something specific in mind, or did you mean the while loop?

Link to comment
Share on other sites

When you say "different approach" do you have something specific in mind, or did you mean the while loop?

 

I mean a completely different approach. It doesn't make sense, to me at least, to loop through consecutive numbers to try and find the number to generate the rounded result. Plus, why calculate the solution, test if the solution matches teh round, then IF the solution doesn't match the rounded solution run a function. Just use the function to do everything.

 

To be honest though, I don't see how that function is supposed to work for anything other than division. Assuming the input numbers are whole numbers the result for addition, subtraction, and multiplication would always be whole numbers as well. Only divisioin would result in decimal numbers.

 

By the way, your function is called round_up, but you are only doing a simple round, which means it could be rounded down. If you want to get the rounded up value you should use ceil().

 

Here is a simple solution that handles division operation. I would do the others, but as I said, I don't see how that would ever be applicable

function returnExactRoundUp($x1, $x2, $op)
{
    switch($op)
    {
        case '/':
            if(($x1/$x2)<ceil($x1/$x2)) {  $x1 = $x2 * ceil($x1/$x2); }
            $result = ceil($x1/$x2);
            break;
    }
    return array('num1' => $x1, 'num2' => $x2, 'op'   => $op, 'solution' => $result);
}

$num1 = 3;
$num2 = 5;
$op = '/';

$result = returnExactRoundUp($num1, $num2, $op);
print_r($result);

Link to comment
Share on other sites

Please tell me that this comes with time and I'm not stupid :/

 

I took a way too long road, when it was all so easy.

 

Note to myself:

- brain storm more before head jumping into a script.

 

Thank you a lot for rescuing my day :D

 

Just by writing this small equation script I learned way more today, than building websites with PHP. It's a whole different way of working.

 

I will keep on working on it though.

 

Link to comment
Share on other sites

Please tell me that this comes with time and I'm not stupid :/

Yes and no. As far as your intelligence goes, I can't say - I don't know you well enough

 

Note to myself:

- brain storm more before head jumping into a script.

 

EXACTLY!

 

My position is that programming is like art. You can teach anyone the fundamentals of painting a picture, but whether the picture is any good or not is really an innate ability. Humans (most anyway) have the ability to think logically but can't transfer that logic to programming. In the above situation you simply needed to go throughthe process of how YOU would have solved the problem. If you had two numbers that, when divided, resulted in a decmial and you wanted to change the numerator to get to the next highest whole number would you really increate the number by 1, test the result, and then continue that till you found the solution? I wouldn't - which is why I came to the solution above.

 

Here is how I would think it through using an example:

18 / 5 = 3.6

OK, I want to change the numerator so result will be equal to that result rounded up to the next highest whole number (4). So, I need to use ceil() on the result. Now what? Well, since I am going to change the numerator to an unknown value and I have known values for the denominator and the result I know have a simple equation: X / 5 = 4, which can then be converted to x = 5 * 4.

Link to comment
Share on other sites

Here is how I would think it through using an example:

18 / 5 = 3.6

OK, I want to change the numerator so result will be equal to that result rounded up to the next highest whole number (4). So, I need to use ceil() on the result. Now what? Well, since I am going to change the numerator to an unknown value and I have known values for the denominator and the result I know have a simple equation: X / 5 = 4, which can then be converted to x = 5 * 4.

 

Ok this makes much more sense, and after all it seems so simple now. This is high school stuff, I could have solved it this way on paper too.

 

So a good approach would be to think how *I* would solve it if somebody gave me that problem in real life.

 

And THEN think about how to translate it into a programming language.

 

Logical and creative (both) thinking play a big role on how efficient you solve a problem. My problem was that I wasn't seeing the forest for the trees, because I head jumped into the script, and just fooled around.

 

Next time I approach a script, I'll solve it on big paper first before I even touch the keyboard, and I'll see how well I do then.

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.