使用结构体在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";
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP