Re: Help converting C to PHP
| From: | Tom Atkinson | Date: | Fri, 22 Sep 2006 05:29:17 +0000 |
| Subject: | Re: Help converting C to PHP | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-242059@lists.php.net to get a copy of this message | ||
I have solved the problem. The variables are declared as and forced to remain integers in C but PHP converts them to float during division. This messed up the maths. Also there was a slight difference in formatting for printf().
Tom Atkinson wrote:
Hello, I am attempting to convert this code for generating the digits of pi from the original C (below) to PHP. long k=4e3,p,a[337],q,t=1e3; main(j){for(;a[j=q=0]+=2,--k;) for(p=1+2*k;j<337;q=a[j]*k+q%p*t,a[j++]=q/p) k!=j>2?:printf("%.3d",a[j-2]%t+q/p/t);} I converted this to a more readable form: long k=4e3; int p; int a[337]; int q; int t=1e3; main(j){ for(;a[j=q=0]+=2,--k;){for(p=1+(2*k);j<337;q=(a[j]*k)+((q%p)*t),a[j++]=(q/p)){ if (j>2 && k==1) printf("%.3d",(a[j-2]%t)+((q/p)/t)); }} } and then changed it to PHP syntax $k=4e3; $p=0; $a=array(); $q=0; $t=1e3; for(;$a[$j=$q=0]+=2,--$k;){ for($p=1+(2*$k);$j<337;$q=($a[$j]*$k)+(($q%$p)*$t),$a[$j++]=($q/$p)){if ($j>2 && $k==1) printf("%.3d",($a[$j-2]%$t)+(($q/$p)/$t));} } The C code correctly gives me pi, but the PHP code gives me some other number which is not pi. What am I missing? Tom.