Swift程序:计算圆的周长
本教程将讨论如何编写一个Swift程序来计算圆的周长。
圆的周长也称为圆的周界。它用于计算圆的边界。例如,如果我们想围住一个圆形的花园,那么借助周长,我们可以计算出覆盖花园边界所需的围栏总量。我们可以用半径或直径来计算圆的周长,这里:
半径 - 它指的是从圆心到圆周上任意一点的距离,通常用r或R表示。或者可以说半径是直径的一半,即r = D/2。
直径 - 它指的是穿过圆心并两端位于圆周上的线段,通常用d或D表示。或者可以说直径是半径的两倍,即D = 2r。
公式
以下是圆的周长公式:
周长 = 2 * π * r
以下是根据直径计算圆周长的公式:
周长 = π * D
使用半径计算周长的算法
步骤1 - 定义半径
步骤2 - 输入π的值
步骤3 - 使用公式:2πr
步骤4 - 打印输出
示例
使用半径计算周长
下面的程序演示了如何使用半径计算圆的周长。
import Foundation
import Glibc
var radius = 10.0
let pi = 3.14
var perimeterOfCircle = 2 * pi * radius
print("Radius of the circle is:", radius)
print("So the perimeter is:", perimeterOfCircle)输出
Radius of the circle is: 10.0 So the perimeter is: 62.800000000000004
在上面的代码中,我们使用以下代码计算圆的周长:
var perimeterOfCircle = 2 * pi * radius
这里的圆的半径是10.0。因此,圆的周长是62.800000000000004。
使用直径计算周长的算法
步骤1 - 定义直径
步骤2 - 输入π的值
步骤3 - 使用公式:πd
步骤4 - 打印输出
示例
使用直径计算周长
下面的程序演示了如何使用直径计算圆的周长。
import Foundation
import Glibc
var diameter = 5.0
let pi = 3.14
var perimeterOfCircle = pi * diameter
print("Diameter of the circle is:", diameter)
print("So the perimeter is:", perimeterOfCircle)输出
Diameter of the circle is: 5.0 So the perimeter is: 15.700000000000001
在上面的代码中,我们使用以下代码计算圆的周长:
var perimeterOfCircle = pi * diameter
这里的圆的直径是5.0。因此,圆的周长是15.7。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP