Python
```python
import math
def calculate_circle_area(radius):
检查半径是否为正数
if radius <= 0:
print("半径必须大于0")
return
计算圆的面积
area = math.pi * radius 2 return area 获取用户输入的半径 radius = float(input("请输入圆的半径:")) 调用函数计算圆的面积 circle_area = calculate_circle_area(radius) 打印结果 print("圆的面积为:", circle_area) ``` C++ ```cpp include include int main() { float r, area; std::cout << "请输入圆的半径: "; std::cin >> r; area = M_PI * r * r; std::cout << "圆的面积为: " << area << std::endl; return 0; } ``` Java ```java import java.util.Scanner; public class CircleArea { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("请输入圆的半径: "); double radius = scanner.nextDouble(); double area = Math.PI * radius * radius; System.out.printf("圆的面积为: %.2f%n", area); } } ``` JavaScript ```javascript function calculateCircleArea(radius) { // 检查半径是否为正数 if (radius <= 0) { console.log("半径必须大于0"); return; } // 计算圆的面积 const area = Math.PI * Math.pow(radius, 2); return area; } // 获取用户输入的半径 const radius = parseFloat(prompt("请输入圆的半径:")); // 调用函数计算圆的面积 const circleArea = calculateCircleArea(radius); // 打印结果 console.log("圆的面积为:", circleArea.toFixed(2)); ``` C ```csharp using System; class Program { static void Main() { Console.Write("请输入圆的半径: "); double radius = Convert.ToDouble(Console.ReadLine()); double area = Math.PI * Math.Pow(radius, 2); Console.WriteLine("圆的面积为: " + area.ToString("F2")); } } ``` Ruby ```ruby def calculate_circle_area(radius) 检查半径是否为正数 if radius <= 0 puts "半径必须大于0" return end 计算圆的面积 area = Math::PI * radius
return area
end
获取用户输入的半径
radius = gets.chomp.to_f
调用函数计算圆的面积
circle_area = calculate_circle_area(radius)
打印结果
puts "圆的面积为: {circle_area.round(2)}"
```
PHP
```php
<?php
function calculate_circle_area($radius) {
// 检查半径是否为正数
if ($radius <= 0) {
echo "半径必须大于0";
return;
}
// 计算圆的面积
$area = M_PI * pow($radius, 2);
return $area;
}
// 获取用户输入的半径
$radius = floatval(readline("请输入圆的半径: "));
// 调用函数计算圆的面积
$circle_area = calculate_circle_area($radius);
// 打印结果
echo "圆的面积为: " . number_format($circle_area, 2) . "\n";
?>
```
Swift