printf

printf函數輸出格式化的字符串

printf(format,arg1,arg2++)

print(format:格式化的字符串,arg爲若干個參數)

$num=5;

$location='樹上';

$format='有%d只猴子在%s';

printf($format,$num,$location);

1

2

3

4

輸出結果:有5只猴子在樹上

$format='有%f只猴子在%s';

1

輸出結果:有5.000000只猴子在在樹上(%f 顯示關於浮點數)

$format='有%.2f只猴子在%s';(%.2f取小數點後兩位)

1

輸出結果::有5.00只猴子在在樹上

注%一定要是半角。

經常使用的%:

%d 顯示包含正負號的十進制(負數,0,正數)。

%s 顯示字符串

%f 顯示關於浮點數

sprintf

sprintf($format,$num,$location);

1

輸出結果:沒有輸出(sprintf不做任何輸出)

綜上所述:printf有輸出,sprintf沒有輸出,但是可以返回結果

爲了解決這個問題,可以採用以下的方式

$num = 5;

$location = '樹上';

$format = '有%d只猴子在%s';//格式化字符串

$str = sprintf($format,$num,$location);

echo $str;

1

2

3

4

5

輸出結果:有5只猴子在樹上(把sprintf放到變量裏,輸出變量)

也可以這樣改

$num = 5;

$location = '樹上';

$format = '有%d只猴子在%s';//格式化字符串

echo sprintf($format,$num,$location);

1

2

3

4

輸出結果:有5只猴子在樹上

查看原文 >>
相關文章