使用結構體在C++程式中新增兩個距離(英寸-英尺)


結構體是不同資料型別項的集合。它在建立具有不同資料型別記錄的複雜資料結構方面非常有用。結構體用`struct`關鍵字定義。

結構體示例如下:

struct DistanceFI {
   int feet;
   int inch;
};

上述結構體以英尺和英寸的形式定義距離。

下面是一個使用C++結構體新增兩個英尺英寸距離的程式:

示例

 線上演示

#include <iostream>

using namespace std;
struct DistanceFI {
   int feet;
   int inch;
};
int main() {
   struct DistanceFI distance1, distance2, distance3;
   cout << "Enter feet of Distance 1: "<<endl;
   cin >> distance1.feet;
   cout << "Enter inches of Distance 1: "<<endl;
   cin >> distance1.inch;

   cout << "Enter feet of Distance 2: "<<endl;
   cin >> distance2.feet;
   cout << "Enter inches of Distance 2: "<<endl;
   cin >> distance2.inch;

   distance3.feet = distance1.feet + distance2.feet;
   distance3.inch = distance1.inch + distance2.inch;

   if(distance3.inch > 12) {
      distance3.feet++;
      distance3.inch = distance3.inch - 12;
   }
   cout << endl << "Sum of both distances is " << distance3.feet << " feet and " << distance3.inch << " inches";
   return 0;
}

輸出

上述程式的輸出如下

Enter feet of Distance 1: 5
Enter inches of Distance 1: 9
Enter feet of Distance 2: 2
Enter inches of Distance 2: 6
Sum of both distances is 8 feet and 3 inches

在上述程式中,定義了結構體`DistanceFI`,其中包含英尺和英寸的距離。如下所示:

struct DistanceFI{
   int feet;
   int inch;
};

從使用者那裡獲取要新增的兩個距離的值。如下所示:

cout << "Enter feet of Distance 1: "<<endl;
cin >> distance1.feet;
cout << "Enter inches of Distance 1: "<<endl;
cin >> distance1.inch;

cout << "Enter feet of Distance 2: "<<endl;
cin >> distance2.feet;
cout << "Enter inches of Distance 2: "<<endl;
cin >> distance2.inch;

分別新增兩個距離的英尺和英寸。如果英寸大於12,則將1加到英尺中,並從英寸中減去12。這是因為1英尺=12英寸。這段程式碼如下:

distance3.feet = distance1.feet + distance2.feet;
distance3.inch = distance1.inch + distance2.inch;
if(distance3.inch > 12) {
   distance3.feet++;
   distance3.inch = distance3.inch - 12;
}

最後顯示新增後的距離的英尺和英寸值。如下所示:

cout << endl << "Sum of both distances is " << distance3.feet << " feet and " << distance3.inch << " inches";

更新於:2020年6月25日

652 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.