1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 struct CDAccount 7 { 8 double balance; //余额 9 double rate; //利息 10 int term; //存期 11 }; 12 13 struct Date 14 { 15 int year; 16 int month; 17 int day; 18 }; 19 20 struct Person 21 { 22 string name; 23 Date birthday; 24 CDAccount account; 25 26 }; 27 28 //**************************************** 29 void get_data(CDAccount& account); 30 double caculate_balance(CDAccount account); 31 Person get_person_data(void); 32 void display_person(Person* person); 33 34 35 36 //*************************************** 37 //process entry 38 int main(int argc,char* argv[]) try 39 { 40 //********************* 41 //演示结构体的一般用法 42 CDAccount marry; 43 44 //获取数据 45 get_data(marry); 46 47 //计算利息 结构体成员赋值 48 marry.balance = caculate_balance(marry); 49 50 //输出信息 51 cout<<"marry的账户余额为:"<<marry.balance<<endl; 52 53 CDAccount bob; 54 55 //结构体整体赋值 56 bob = marry; 57 58 cout<<"bob的账户余额为:"<<bob.balance<<endl ; 59 60 //结构体初始化 61 CDAccount lee = {3000,0.12,3}; 62 63 //visual c++ 不支持下面的初始化方式, g++支持,属于实现的扩展,本身不是C++的一部分功能 64 /*CDAccount jack = { 65 .balance = 4000; 66 .rate = 0.5; 67 .term = 10; 68 }*/ 69 70 //*************************** 71 //演示嵌套结构体的用法 72 Person dudo; 73 74 //输入个人信息, 函数返回结构体 75 dudo = get_person_data(); 76 77 display_person(&dudo); 78 79 80 char ch; 81 cin>>ch; 82 return 0; 83 } 84 catch(...) 85 { 86 cout<<"捕捉到异常"<<endl; 87 } 88 89 90 //获取数据 函数传递结构引用 91 void get_data(CDAccount& account) 92 { 93 cout<<"请输入本金、利率和存期(存期以月份计算,最大为12个月):"; 94 cin>>account.balance; 95 cin>>account.rate ; 96 cin>>account.term ; 97 } 98 99 100 //计算余额 函数传递结构体 101 double caculate_balance(CDAccount account) 102 { 103 double balance; 104 105 balance = account.balance + account.balance * account.rate * account.term; 106 107 return balance; 108 } 109 110 //获取个人信息 111 Person get_person_data(void) 112 { 113 Person person; 114 cout<<"请输入账户名称,生日(年、月、日):"; 115 cin>>person.name >>person.birthday.year >>person.birthday.month>>person.birthday.day ; 116 117 cout<<"请输入"<<person.name <<"的信息,本金、利息和存期(存期最大12个月):"; 118 cin>>person.account.balance >>person.account.rate >>person.account.term ; 119 120 return person; 121 } 122 123 124 //显示信息, 演示结构体指针变量的使用 125 void display_person(Person* person) 126 { 127 cout<<"名字是:"<<person->name<<endl; 128 cout<<"生日是:"<<person->birthday.year<<"-"<<person->birthday.month<<"-"<<person->birthday.day<<endl; 129 cout<<"账户信息:"<<person->account.balance<<"\t"<<person->account.rate<<‘\t‘<<person->account.term<<endl; 130 131 }
时间: 2024-11-05 12:16:48