JavaScript,在网页上输出半径为 3 的圆的面积和周长
时间: 2023-09-14 20:06:24 浏览: 63
可以使用以下代码实现:
```javascript
var radius = 3;
var area = Math.PI * radius * radius;
var circumference = 2 * Math.PI * radius;
document.write("半径为 " + radius + " 的圆,面积为 " + area.toFixed(2) + ",周长为 " + circumference.toFixed(2));
```
代码解释:首先定义一个变量 radius,表示圆的半径为 3;然后使用 Math.PI * radius * radius 计算圆的面积;使用 2 * Math.PI * radius 计算圆的周长;最后使用 document.write() 将结果输出到网页上。toFixed() 函数用于将小数点后的位数控制在 2 位。
相关问题
设计JavaScript 程序,在网页上输出半径为 3 的圆的面积和周长。
可以使用以下 JavaScript 代码来计算半径为 3 的圆的面积和周长,并将结果输出到网页上:
```html
<!DOCTYPE html>
<html>
<head>
<title>计算圆的面积和周长</title>
<script>
function calculate() {
var radius = 3;
var area = Math.PI * radius * radius;
var perimeter = 2 * Math.PI * radius;
document.getElementById("result").innerHTML = "半径为 3 的圆的面积为:" + area.toFixed(2) + ",周长为:" + perimeter.toFixed(2);
}
</script>
</head>
<body>
<button onclick="calculate()">计算圆的面积和周长</button>
<p id="result"></p>
</body>
</html>
```
在 HTML 页面中,我们定义了一个按钮和一个用于输出结果的段落元素。当用户点击按钮时,会调用 `calculate()` 函数来计算圆的面积和周长,并将结果输出到段落元素中。其中,`Math.PI` 表示圆周率,`toFixed(2)` 表示保留两位小数。
用javascript计算半径为5的圆的周长和面积
可以使用以下代码计算半径为5的圆的周长和面积:
```javascript
const radius = 5;
const circumference = 2 * Math.PI * radius;
const area = Math.PI * radius * radius;
console.log(`半径为${radius}的圆的周长为${circumference.toFixed(2)},面积为${area.toFixed(2)}`);
```
输出结果为:
```
半径为5的圆的周长为31.42,面积为78.54
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)