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";