php用while写出自然数,PHP 自然对数

该博客介绍了如何利用log函数计算一个十进制或任意基数整数的位数,并展示了如何使用这个函数来动态格式化一列整数的显示,使其在固定宽度的列中整齐排列。示例包括计算2的24次幂的十进制位数,以及以二进制形式表示10亿的位数。此外,还提供了一个函数用于打印随机整数列表的表格形式。
摘要由CSDN通过智能技术生成

#     How many digits does an integer have?

#--------------------------------------------------------functiondigit_count($n,$base=10) {

if($n==0) return1;

if($base==10) {# using the built-in log10(x)

# might be more accurate than log(x)/log(10).return1+floor(log10(abs($n)));

}else{# here  logB(x) = log(x)/log(B) will have to do.return1+floor(log(abs($n))/log($base));

}

}# Example:  How many decimal digits for 2 to the power 24?echodigit_count(pow(2,24));# Example: How many bits to write 1 billion in binary, last century?if($country_code=='US') echodigit_count(pow(10,9),2);

if($country_code=='UK') echodigit_count(pow(10,12),2);#--------------------------------------------------------

#     Using log to format columns.

#--------------------------------------------------------

# Suppose we have a dynamically generated list of integers,

# and want to present them as a table. The use of log10 in

# our digit_count helps calculate the proper format string.functionprint_list_of_ints($ints,$line_width=40) {# Apply our digit_count to the max int among ints.$field_width=2+digit_count(max($ints));# Create format string for printf.$format="%${field_width}d";$ints_per_line=floor($line_width/$field_width);$border=str_repeat("-",$ints_per_line*$field_width);

echo"\n$border\n";

foreach($intsas$count=>$int) {

if($countand ($count%$ints_per_line==0)) echo"\n";printf($format,$int);

}

echo"\n$border\n";

}# To generate an example, here is a basic function

# returning a list of (pseudo) random numbers.functionrands($how_many) {

for($i=0;$i

return$rands;

}# Example:  A list of random ints dynamically formatted into columns.print_list_of_ints(rands(11));/* Sample output. Numbers and fonts vary. Visualize monospace!

------------------------------------

1093146637   244503173  1346204527

638304372   140216732  1054707210

573915416  1728677954  2038899669

534854768    12674586

------------------------------------

*/?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值