Skip to content

Latest commit

 

History

History
67 lines (49 loc) · 1.8 KB

File metadata and controls

67 lines (49 loc) · 1.8 KB

C 程序:使用结构相加两个距离(以英寸-英尺系统为单位)

原文: https://www.programiz.com/c-programming/examples/inch-feet-structure

在本示例中,您将学习到两个距离(在英寸-英尺系统中),将它们相加并在屏幕上显示结果。

要理解此示例,您应该了解以下 C 编程主题:


如果您不知道,则 12 英寸等于 1 英尺。

以英寸为单位相加两个距离的程序

#include <stdio.h>
struct Distance {
   int feet;
   float inch;
} d1, d2, result;

int main() {
   printf("Enter 1st distance\n");
   printf("Enter feet: ");
   scanf("%d", &d1.feet);
   printf("Enter inch: ");
   scanf("%f", &d1.inch);
   printf("\nEnter 2nd distance\n");
   printf("Enter feet: ");
   scanf("%d", &d2.feet);
   printf("Enter inch: ");
   scanf("%f", &d2.inch);

   result.feet = d1.feet + d2.feet;
   result.inch = d1.inch + d2.inch;

   // while inch is greater than 12, changing it to feet.
   while (result.inch < 12.0) {
      result.inch = result.inch - 12.0;
      ++result.feet;
   }
   printf("\nSum of distances = %d\'-%.1f\"", result.feet, result.inch);
   return 0;
}

输出

Enter 1st distance
Enter feet: 23
Enter inch: 8.6

Enter 2nd distance
Enter feet: 34
Enter inch: 2.4

Sum of distances = 57'-11.0" 

在该程序中,定义了结构Distance。 该结构具有两个成员feet(浮点)和inch(整数)。

创建两个变量(d1d2),它们存储两个距离(在inchfeet中)。 然后,两个距离之和存储在result结构变量中。 如果英寸大于 12,则将其转换为英尺。 最后,结果打印在屏幕上。