C++_系列自学课程_第_12_课_结构体

时间:2021-10-12 23:21:53
 #include <iostream>
#include <string> using namespace std; struct CDAccount
{
double balance; //余额
double rate; //利息
int term; //存期
}; struct Date
{
int year;
int month;
int day;
}; struct Person
{
string name;
Date birthday;
CDAccount account; }; //****************************************
void get_data(CDAccount& account);
double caculate_balance(CDAccount account);
Person get_person_data(void);
void display_person(Person* person); //***************************************
//process entry
int main(int argc,char* argv[]) try
{
//*********************
//演示结构体的一般用法
CDAccount marry; //获取数据
get_data(marry); //计算利息 结构体成员赋值
marry.balance = caculate_balance(marry); //输出信息
cout<<"marry的账户余额为:"<<marry.balance<<endl; CDAccount bob; //结构体整体赋值
bob = marry; cout<<"bob的账户余额为:"<<bob.balance<<endl ; //结构体初始化
CDAccount lee = {,0.12,}; //visual c++ 不支持下面的初始化方式, g++支持,属于实现的扩展,本身不是C++的一部分功能
/*CDAccount jack = {
.balance = 4000;
.rate = 0.5;
.term = 10;
}*/ //***************************
//演示嵌套结构体的用法
Person dudo; //输入个人信息, 函数返回结构体
dudo = get_person_data(); display_person(&dudo); char ch;
cin>>ch;
return ;
}
catch(...)
{
cout<<"捕捉到异常"<<endl;
} //获取数据 函数传递结构引用
void get_data(CDAccount& account)
{
cout<<"请输入本金、利率和存期(存期以月份计算,最大为12个月):";
cin>>account.balance;
cin>>account.rate ;
cin>>account.term ;
} //计算余额 函数传递结构体
double caculate_balance(CDAccount account)
{
double balance; balance = account.balance + account.balance * account.rate * account.term; return balance;
} //获取个人信息
Person get_person_data(void)
{
Person person;
cout<<"请输入账户名称,生日(年、月、日):";
cin>>person.name >>person.birthday.year >>person.birthday.month>>person.birthday.day ; cout<<"请输入"<<person.name <<"的信息,本金、利息和存期(存期最大12个月):";
cin>>person.account.balance >>person.account.rate >>person.account.term ; return person;
} //显示信息, 演示结构体指针变量的使用
void display_person(Person* person)
{
cout<<"名字是:"<<person->name<<endl;
cout<<"生日是:"<<person->birthday.year<<"-"<<person->birthday.month<<"-"<<person->birthday.day<<endl;
cout<<"账户信息:"<<person->account.balance<<"\t"<<person->account.rate<<'\t'<<person->account.term<<endl; }