我试图制作的表格应该:
第一个表应包括使用 PHP 计算圆的面积和周长的结果
此外,我正在尝试使答案四舍五入到浮点数的前 2 位小数。任何帮助将不胜感激。
<!DOCTYPE html>
<!--
Author:Randy Gilman
-->
<?php
$cir_area = M_PI * sqrt(2.65)
$cir_circum = 2 * M_PI * 2.65
?>
<html>
<head>
<meta charset="UTF-8">
<title> Randy's Table</title>
</head>
<body>
<table border = "5px">
<tr>
<th> Shape </th>
<th> Parameter and Values </th>
<th> Area </th>
<th> Perimeter </th>
</tr>
<tr>
<th> Circle </th>
<th> radius = 2.65 meters </th>
<th> <?php echo "$cir_area"?> </th>
<th> <?php echo "$cir_circum"?> </th>
</tr>
</table>
</body>
</html>
PHP 使用分号来结束一行:
echo "Hello";
如果尝试运行代码,则会收到此错误:
Message : syntax error, unexpected '$cir_circum' (T_VARIABLE)
这意味着,您忘记用分号结束行。
你的 PHP 应该看起来像这样:
<?php
$cir_area = M_PI * sqrt(2.65);
$cir_circum = 2 * M_PI * 2.65;
?>
要对数字进行舍入,您可以使用number_format
:
<?php
$cir_area = number_format(M_PI * sqrt(2.65), 2);
$cir_circum = number_format(2 * M_PI * 2.65, 2);
?>
<th> <?php echo number_format($cir_area,2);?> </th>
<th> <?php echo number_format($cir_circum,2);?> </th>
sqrt()
("平方根"的缩写)是一个计算其参数平方根的函数。
圆面积的公式不使用平方根,而是使用其半径的平方(即 R*R
)。
计算应为:
$radius = 2.65; // put it into a variable for clear and easy to change code
$cir_area = M_PI * $radius * $radius;
$cir_circum = 2 * M_PI * $radius;
备注:PHP 语句以分号 ( ;
结尾)。你忘了把它放在你的代码中,这就是为什么它不编译并显示错误(或根本没有)而不是预期的HTML输出。
您可以使用函数number_format()
使用指定数量的十进制数字来显示浮点数。
代码:
<tr>
<td>Circle</td>
<td>radius = <?php echo(number_format($radius, 2)); ?> meters</td>
<td><?php echo(number_format($cir_area, 2)); ?> square meters</td>
<td><?php echo(number_format($cir_circum, 2)); ?> meters</td>
</tr>
请在 PHP $cir_area = M_PI * sqrt(2.65);
中的每个语句后使用分号,并且对于四舍五入到浮点数的前 2 位小数,您可以使用string number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )
在您的代码中,我进行了一些更改及其工作
$cir_area = number_format(M_PI * sqrt(2.65), 2, '.', '');
$cir_circum = number_format(2 * M_PI * 2.65, 2, '.', '');
<tr>
<th> <?php echo $cir_area?> </th>
<th> <?php echo $cir_circum?> </th>
</tr>