在 C 语言中计算矩形面积

CCBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,你将学习如何在 C 编程语言中使用用户自定义函数来计算矩形的面积。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") c/FunctionsGroup -.-> c/function_parameters("`Function Parameters`") c/UserInteractionGroup -.-> c/user_input("`User Input`") subgraph Lab Skills c/function_declaration -.-> lab-136085{{"`在 C 语言中计算矩形面积`"}} c/function_parameters -.-> lab-136085{{"`在 C 语言中计算矩形面积`"}} c/user_input -.-> lab-136085{{"`在 C 语言中计算矩形面积`"}} end

使用函数计算矩形的面积

在本实验中,你将学习如何使用函数计算矩形的面积。

  1. 在 WebIDE 中创建一个名为 rectangle.c 的新文件。

  2. 将以下代码添加到 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,它接受两个参数 hw,分别表示矩形的高度和宽度。该函数通过将高度和宽度相乘来计算矩形的面积,并返回结果。

    main 函数从用户那里读取高度和宽度值,调用 area 函数计算面积,然后打印结果。

  3. 保存 rectangle.c 文件。

  4. 打开终端并导航到 rectangle.c 文件所在的目录。

  5. 使用以下命令编译 rectangle.c 文件:

    gcc rectangle.c -o rectangle

    该命令编译 C 代码并生成一个名为 rectangle 的可执行文件。

  6. 使用以下命令运行 rectangle 可执行文件:

    ./rectangle
  7. 当提示时,输入矩形的高度和宽度。

  8. 程序将计算并打印矩形的面积。

总结

完成本实验后,你将能够在 C 编程语言中使用用户自定义函数计算矩形的面积。

您可能感兴趣的其他 C 教程