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
https://forums.phpfreaks.com/topic/86794-solved-while-loop-issue/
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?

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.

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 ?

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.