我正在尝试执行乘法,但我无法使用str_pad进行格式化,但我无法以此格式进行格式化
例如,如果我想要成倍增加。 421乘675
I want to do exactly in this format
4 2 1
x 6 7 5
__________
2 1 0 5
2 9 4 7 x
2 5 2 6 x x
________________
2 8 4 1 7 5
但填充中存在问题我无法在str_pad中显示这些x
,当我使用此格式时它无法正常工作。
它显示如下
这是代码
$multiplier = 421;
$multiplicand = 675;
$result = $multiplier * $multiplicand;
$pad_max = strlen($result);
$multiplicand_values = str_split($multiplicand);
echo str_pad($multiplier, $pad_max, " ", STR_PAD_LEFT) . PHP_EOL;
echo "<br/>";
echo str_pad("x" . $multiplicand, $pad_max, " ", STR_PAD_LEFT) . PHP_EOL;
echo "<br/>";
echo str_pad("-", $pad_max, "-", STR_PAD_LEFT) . PHP_EOL;
echo "<br/>";
for($i = 0; null !== ($digit = array_pop($multiplicand_values)); ++$i)
{
echo str_pad($multiplier * $digit * pow(1, $i), $pad_max, " ", STR_PAD_LEFT) . PHP_EOL;
echo "<br/>";
}
echo "<br/>";
echo str_pad("-", $pad_max, "-", STR_PAD_LEFT) . PHP_EOL;
echo "<br/>";
echo str_pad($result, $pad_max, " ", STR_PAD_LEFT) . PHP_EOL;
答案 0 :(得分:1)
您只需尝试使用sprintf:
$multiplier = 421;
$multiplicand = 675;
$result = $multiplier * $multiplicand;
$pad_max = strlen($result);
$multiplicand_values = str_split($multiplicand);
echo sprintf("%${pad_max}s", $multiplier)."<br/>";
echo sprintf("%${pad_max}s", "x".$multiplicand)."<br/>";
echo str_repeat("_", $pad_max)."<br/>";
for($i = 0; null !== ($digit = array_pop($multiplicand_values)); ++$i)
{
$value = $multiplier * $digit * pow(1, $i);
$xValue = str_repeat("x", $i);
echo sprintf("%${pad_max}s", $value.$xValue)."<br/>";
}
echo str_repeat("_", $pad_max)."<br/>";
echo $result;
结果:
421
x675
______
2105
2947x
2526xx
______
284175
获取此输出:
4 2 1
x 6 7 5
___________
2 1 0 5
2 9 4 7 x
2 5 2 6 x x
___________
2 8 4 1 7 5
你需要分开单词。我使用了wordwrap:
$multiplier = 421;
$multiplicand = 675;
$result = $multiplier * $multiplicand;
$pad_max = strlen(word_Wrap($result));
$multiplicand_values = str_split($multiplicand);
echo sprintf("%${pad_max}s", word_Wrap($multiplier))."<br/>";
echo sprintf("%${pad_max}s", word_Wrap("x".$multiplicand))."<br/>";
echo str_repeat("_", $pad_max)."<br/>";
for($i = 0; null !== ($digit = array_pop($multiplicand_values)); ++$i)
{
$value = $multiplier * $digit * pow(1, $i);
$xValue = str_repeat("x", $i);
echo sprintf("%${pad_max}s", word_Wrap($value.$xValue))."<br/>";
}
echo str_repeat("_", $pad_max)."<br/>";
echo word_Wrap($result);
function word_Wrap($value) {
return wordwrap($value, 1, " ", true);
}