介绍
在本实验中,你将学习如何在 C 编程语言中使用用户自定义函数来计算矩形的面积。
在本实验中,你将学习如何在 C 编程语言中使用用户自定义函数来计算矩形的面积。
在本实验中,你将学习如何使用函数计算矩形的面积。
在 WebIDE 中创建一个名为 rectangle.c
的新文件。
将以下代码添加到 rectangle.c
文件中:
#include <stdio.h>
int area(int h, int w)
{
int area = h * w;
return area;
}
void main()
{
int height, width;
printf("Enter the height of the rectangle: ");
scanf("%d", &height);
printf("Enter the width of the rectangle: ");
scanf("%d", &width);
printf("The area of the rectangle = %d\n\n\n", area(height, width));
}
这段代码定义了一个函数 area
,它接受两个参数 h
和 w
,分别表示矩形的高度和宽度。该函数通过将高度和宽度相乘来计算矩形的面积,并返回结果。
main
函数从用户那里读取高度和宽度值,调用 area
函数计算面积,然后打印结果。
保存 rectangle.c
文件。
打开终端并导航到 rectangle.c
文件所在的目录。
使用以下命令编译 rectangle.c
文件:
gcc rectangle.c -o rectangle
该命令编译 C 代码并生成一个名为 rectangle
的可执行文件。
使用以下命令运行 rectangle
可执行文件:
./rectangle
当提示时,输入矩形的高度和宽度。
程序将计算并打印矩形的面积。
完成本实验后,你将能够在 C 编程语言中使用用户自定义函数计算矩形的面积。