📜  C++程序使用结构添加两个距离(以英寸-英尺为单位)

📅  最后修改于: 2020-09-25 06:10:15             🧑  作者: Mango

该程序需要两个距离(以英寸英尺为单位),将其相加并在屏幕上显示结果。

示例:使用结构添加距离

#include 
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;
}

输出

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

在这个程序中,一个结构Distance包含两个数据成员( inchfeet )被声明为存储在英寸英尺系统的距离。

在此,创建两个结构变量d1d2来存储用户输入的距离。并且, sum变量存储距离的和。

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