正方形面积的编程怎么写

时间:2025-01-28 05:10:56 网络游戏

Python

```python

def calculate_square_area(side_length):

return side_length 2

side = float(input("请输入正方形的边长:"))

area = calculate_square_area(side)

print("正方形的面积为:", area)

```

C语言

```c

include

int main() {

float side, area;

printf("请输入正方形的边长:");

scanf("%f", &side);

area = side * side;

printf("正方形的面积为:%.2f\n", area);

return 0;

}

```

Java

```java

import java.util.Scanner;

public class SquareArea {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("请输入正方形的边长: ");

double side = scanner.nextDouble();

double area = side * side;

System.out.printf("正方形的面积为: %.2f%n", area);

}

}

```

C++

```cpp

include

int main() {

double side, area;

std::cout << "请输入正方形的边长: ";

std::cin >> side;

area = side * side;

std::cout << "正方形的面积为: " << std::fixed << std::setprecision(2) << area << std::endl;

return 0;

}

```

JavaScript

```javascript

function calculateSquareArea(sideLength) {

return sideLength * sideLength;

}

const side = parseFloat(prompt("请输入正方形的边长:"));

const area = calculateSquareArea(side);

alert("正方形的面积为: " + area);

```

这些代码示例均通过获取用户输入的正方形边长,然后计算其平方来得到正方形的面积,并输出结果。你可以根据需要选择合适的编程语言进行实现。