# C++ 程序：使用结构相加两个距离（以英寸和英尺为单位）

> 原文： [https://www.programiz.com/cpp-programming/examples/inch-feet-structure](https://www.programiz.com/cpp-programming/examples/inch-feet-structure)

#### 该程序需要两个距离（以英寸和英尺为单位），将其相加并在屏幕上显示结果。

要理解此示例，您应该了解以下 [C++ 编程](/cpp-programming "C++ tutorial")主题：

*   [C++ 结构](/cpp-programming/structure)
*   [C++ `if`，`if...else`和嵌套`if...else`](/cpp-programming/if-else)

* * *

* * *

## 示例：使用结构相加距离

```cpp
#include <iostream>
using namespace std;

struct Distance{
    int feet;
    float inch;
}d1 , d2, sum;

int main()
{
    cout << "Enter 1st distance," << endl;
    cout << "Enter feet: ";
    cin >> d1.feet;
    cout << "Enter inch: ";
    cin >> d1.inch;

    cout << "\nEnter information for 2nd distance" << endl;
    cout << "Enter feet: ";
    cin >> d2.feet;
    cout << "Enter inch: ";
    cin >> d2.inch;

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

    // changing to feet if inch is greater than 12
    if(sum.inch > 12)
    {
        ++ sum.feet;
        sum.inch -= 12;
    } 

    cout << endl << "Sum of distances = " << sum.feet << " feet  " << sum.inch << " inches";
    return 0;
} 
```

**输出**

```cpp
Enter 1st distance,
Enter feet: 6
Enter inch: 3.4

Enter information for 2nd distance
Enter feet: 5
Enter inch: 10.2

Sum of distances = 12 feet  1.6 inches 
```

在此程序中，声明了一个包含两个数据成员（`feet`和`inch`）的结构`Distance`，以英寸-英尺系统存储距离。

在此，创建两个结构变量`d1`和`d2`来存储用户输入的距离。 并且，`sum`变量存储距离之和。

如果`sum`变量的`feet`的值大于 12，则`if..else`语句用于将英寸转换为英尺。