易百教程

编写程序:计算房间的面积

要求

从用户那里获读取以英尺和英寸为单位的房间长度和宽度。然后计算并输出面积,小数点后面有两位小数。

提示

1英尺相当于12英寸,1码相当于3英尺。

参考实现代码:

// 计算房间的面积
#include <stdio.h>

int main(void)
{
  double length = 0.0;                     // Room length in yards
  double width = 0.0;                      // Room width in yards
  long feet = 0L;                          // A whole number of feet
  long inches = 0L;                        // A whole number of inches
  const long inches_per_foot = 12L;
  const double inches_per_yard = 36L;

  // Get the length of the room
   printf("Enter the length of the room in feet and inches - whole feet first: ");
   scanf("%ld", &feet);
   printf("                                           ...Now enter the inches: ");
   scanf("%ld", &inches);
   length = (feet*inches_per_foot + inches)/inches_per_yard;

  // Get the width of the room
   printf("Enter the width of the room in feet and inches - whole feet first: ");
   scanf("%ld", &feet);
   printf("                                          ...Now enter the inches: ");
   scanf("%ld", &inches);
   width = (feet*inches_per_foot + inches)/inches_per_yard;

   // Output the area
   printf("The area of the room is %.2f square yards.
", length*width);
   return 0;
}

编译并执行上面代码,得到以下结果:

hema@ubuntu:~/book$ gcc main.c
hema@ubuntu:~/book$ ./a.out
Enter the length of the room in feet and inches - whole feet first: 12
                                           ...Now enter the inches: 21
Enter the width of the room in feet and inches - whole feet first: 12
                                          ...Now enter the inches: 22
The area of the room is 21.13 square yards.