C语言教程
C语言控制语句
C语言函数
C语言数组
C语言指针
C语言字符串
C语言数学函数
C语言结构
C语言文件处理
C预处理器

C 使用结构添加两个距离(英寸-英尺系统)的程序

使用结构添加两个距离(英寸-英尺系统)的 C 程序

在本例中,您将学习获取两个距离(在英寸-英尺系统中),将它们相加并在屏幕上显示结果。
要理解此示例,您应该了解以下C 编程 主题:
C 结构
如果您不知道,12 英寸是 1 英尺。

在英寸-英尺系统中添加两个距离的程序

#include <stdio.h>
struct Distance {
   int feet;
   float inch;
} d1, d2, result;
int main() {
   // take first distance input
   printf("Enter 1st distance\n");
   printf("Enter feet: ");
   scanf("%d", &d1.feet);
   printf("Enter inch: ");
   scanf("%f", &d1.inch);
 
   // take second distance input
   printf("\nEnter 2nd distance\n");
   printf("Enter feet: ");
   scanf("%d", &d2.feet);
   printf("Enter inch: ");
   scanf("%f", &d2.inch);
   
   // adding distances
   result.feet = d1.feet + d2.feet;
   result.inch = d1.inch + d2.inch;
   // convert inches to feet if greater than 12
   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。该结构有两个成员:
英尺-一个整数 英寸-浮动
创建了 struct Distance 类型的两个变量 d1d2。这些变量以英尺和英寸为单位存储距离。
然后,计算这两个距离的总和并将其存储在 result 变量中。最后, result 打印在屏幕上。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4