第七章课后习题
1、定义结构体,对输入年月日计算是该年的第几天
#include<iostream>
using namespace std;
struct Date{
int year;
int month;
int day;
};
int main(){
Date da;
cin>>da.year>>da.month>>da.day;
int a[12]={
31,28,31,30,31,30,31,31,30,31,30,31};
int sum=0;
for(int i=0;i<da.month-1;i++){
sum=sum+a[i];
}
sum=sum+da.day;
if((da.year%4==0&&da.year%100!=0)||(da.year%400==0)){
if(da.month>2){
sum++;
}
}
cout<<sum<<endl;
return 0;
}
2、用函数实现第一题
#include<iostream>
using namespace std;
struct Date{
int year;
int month;
int day;
};
int days(int year,int month,int day){
int a[12]={
31,28,31,30,31,30,31,31,30,31,30,31};
int sum=0;
for(int i=0;i<month-1;i++){
sum=sum+a[i];
}
sum=sum+day;
if((year%4==0&&year%100!=0)||(year%400==0)){
if(month>2){
sum++;
}
}
return sum;
}
int main(){
Date da;
cin>>da.year>>da.month>>da.day;
int sum=days(da.year,da.month,da.day);
cout<<sum<<endl;
return 0;
}
3、结构体数组,学生信息输入打印
#include<iostream>
#include<string>
using namespace std;
struct Student{
int num;
string name;
double score[3];
};
void print(Student a){
cout<<a.num<<'\t'<<a.name<<'\t';
cout<<a.score[0]<<" "<<a.score[1]<<" "<<a.score[2]<<endl;
}
int main(){
Student stu[5];
for(int i=0;i<5;i++){
cin>>stu[i].num >>stu[i].name;
for(int j=0;j<3;j++){
cin>>stu[i].score[j];
}
}
cout<<endl<<"num"<<'\t'<<"name"<<'\t'<<"score"<<endl;
for(int i=0;i<5;i++){
print(stu[i]);
}
return 0;
}
4、第三题加上一个input函数
#include<iostream>
#include<string>
using namespace std;
struct Student{
int num;
string name;
double score[3];
};
void input(Student *a){
cin>>(*a).num >>(*a).name;
for(int j=0;j<3;j++){
cin>>(*a).score[j];
}
}
void print(Student a){
cout<<a.num<<'\t'<<a.name<<'\t';
cout<<a.score[0]<<" "<<a.score[1]<<" "<<a.score[2]<<endl;
}
int main(){
Student stu[5];
Student *p;
p=&stu[0];
for(int i=0;i<5;i++){