Jump to content

[SOLVED] While loop issue


EchoFool

Recommended Posts

I have a while loop which is meant to multiply a number by itself only it gave me a strange ending result...

 

This is what i got:

 

$Level = 10;
		$Check = 0;
		$Power = 1;
		While($Check < $Level){
		$Check = $Check + 1;
		If($Power == 1){
			$Power = $Power + 1;
		}Else{
			$Power = $Power * $Power;
			}




	}
	Echo $Power;

 

And the response is:

1.34078079299E+154

 

Why is that? What did i do wrong.... its meant to loop 10 times. So the $Power should be 1028.. if my maths is correct.

 

Hope you can help.

Link to comment
Share on other sites

In this case a for loop would be better:

 

$level = 10;
$power = 1;

for($i = 0; $i < $level; $i++)
{
if($power == 1)
{
	$power += 1;
}
else {
	$power *= $power;
}
}

 

Why not just use pow() though?

 

I've never heard of pow() ? What is the $i coming from ? Also what is "$i++" ? Is that just to add 1 to its self?

Link to comment
Share on other sites

I tried your for loop and got:

1.34078079299E+154

 

Which is what i got with my while loop.. what is going wrong ?

That's because I simply wrote the for loop as a replacement for your while loop. The problem still persists with the for loop as explained by revraz. I suppose I should have pointed that out.

 

So $power = pow(2, $level); would also work?

Yes.

Link to comment
Share on other sites

I am suppose to multiply the result by itself ...not the step of the level...

 

Example:

 

If i multiply the step of the level by the result the numbers are too low...

 

If result is 12044 then it needs to be 12044 X 12044 not:

 

12044 x 8 (as as example of the step of the level).

 

My maths is poor i been mainly thinking in letters whilst making my scripts as formula's represent any numbers.

 

Daniel - Is that still usable as integer in maths etc or will it crash out due to letters and decimal point ?

 

 

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.