显示计算出的矩形面积
在这一步骤中,你将学习如何使用 C 语言中的 printf()
函数显示计算出的矩形面积。
- 更新
rectangle.c
文件中的 main()
函数以打印计算出的面积:
void main()
{
int height, width, rectangleArea;
printf("Enter the height of the rectangle: ");
scanf("%d", &height);
printf("Enter the width of the rectangle: ");
scanf("%d", &width);
rectangleArea = calculateRectangleArea(height, width);
printf("The area of the rectangle is: %d square units\n", rectangleArea);
}
- 让我们分解输出语句:
printf()
用于显示文本和值
%d
是整数值的格式说明符
rectangleArea
是包含计算面积的变量
square units
用于为结果提供上下文
- 更新完整的
rectangle.c
文件以包含输出语句:
#include <stdio.h>
int calculateRectangleArea(int height, int width)
{
int area = height * width;
return area;
}
void main()
{
int height, width, rectangleArea;
printf("Enter the height of the rectangle: ");
scanf("%d", &height);
printf("Enter the width of the rectangle: ");
scanf("%d", &width);
rectangleArea = calculateRectangleArea(height, width);
printf("The area of the rectangle is: %d square units\n", rectangleArea);
}
编译并运行程序以测试输出显示。
gcc rectangle.c -o rectangle
./rectangle
示例输出:
Enter the height of the rectangle: 5
Enter the width of the rectangle: 10
The area of the rectangle is: 50 square units