Struct là tập hợp các mục khác kiểu dữ liệu. Rất hữu ích tạo cấu trúc dữ liệu phức tạp với các bản ghi khác kiểu. Struct định nghĩa bằng từ khóa struct.
Ví dụ struct:
struct DistanceFI { int feet; int inch; };Struct trên định nghĩa khoảng cách dạng feet và inch.
Chương trình cộng hai khoảng cách inch-feet dùng struct trong C++:
Ví dụ
#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; }Kết quả
Kết quả chương trình:
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
Trong chương trình, struct DistanceFI chứa khoảng cách feet và inch:
struct DistanceFI{ int feet; int inch; };Giá trị hai khoảng cách cần cộng lấy từ người dùng:
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;
Feet và inch của hai khoảng cách cộng riêng biệt. Nếu inch lớn hơn 12, cộng 1 feet và trừ 12 inch vì 1 feet = 12 inch:
distance3.feet = distance1.feet + distance2.feet; distance3.inch = distance1.inch + distance2.inch; if(distance3.inch > 12) { distance3.feet++; distance3.inch = distance3.inch - 12; }Cuối cùng hiển thị feet và inch của khoảng cách tổng:
cout << endl << "Sum of both distances is " << distance3.feet << " feet and " << distance3.inch << " inches";