第17周项目4-当年第几天(结构体)

本文介绍了一个程序,用于计算给定日期是该年份的第几天。通过输入年、月、日,程序能够输出相应的天数。

问题及代码:

/* 
*Copyright (c)2014,烟台大学计算机与控制工程学院 
*All rights reserved. 
*文件名称:num.cpp 
*作    者:单昕昕 
*完成日期:2014年12月18日 
*版 本 号:v1.0 
* 
*问题描述:当年第几天。 
*程序输入:日期。
*程序输出:当年第几天。
*/  
#include <iostream>
using namespace std;
int day(int y, int m, int d);
struct Date
{
    int year;
    int month;
    int day;
};
int main()
{
    Date date;
    int days;
    cout<<"input year,month,day:";
    cin>>date.year>>date.month>>date.day;
    days=day(date.year,date.month,date.day);
    cout<<date.month<<"月"<<date.day<<"日是"<<date.year<<"年的第"<<days<<"天."<<endl;
    return 0;
}
int day(int y, int m, int d)
{
    int sum=0,n;
    for(n=1; n<m; ++n)
    {
        if ((y%4==0&&y%100!=0)||y%400==0)
        {
            if(n==1||n==3||n==5||n==7||n==8||n==10||n==12)
                sum+=31;
            else if (n==2)
                sum+=29;
            else
                sum+=30;
        }
        else
        {
            if(n==1||n==3||n==5||n==7||n==8||n==10||n==12)
                sum+=31;
            else if (n==2)
                sum+=28;
            else
                sum+=30;
        }
    }
    sum+=d;
    return (sum);
}

 

运行结果:

 

知识点总结:

当年第几天(结构体)。

 

学习心得:

额。。都是以前的程序改改的。

C语言允许用户自己建立由不同类型数据组成的组合型的数据结构,它称为结构体。struct是声明结构体类型时所必须使用的关键字,结构体类型的名字是由关键字struct和结构体名组合而成的(例如struct Student),它和系统提供的标准类型int、char等具有相似的作用,可以用来定义变量(例如struct Student stu1,stu2;)[^1]。 ### 结构体的定义 结构体定义的一般形式如下: ```c struct 结构体名 { 数据类型 成员名1; 数据类型 成员名2; // 可以有更多成员 }; ``` 例如定义一个表示学生信息的结构体: ```c struct Student { char name[50]; int age; float score; }; ``` ### 结构体变量的定义 有了结构体类型后,可以用它来定义变量,定义方式有以下几种: - 先定义结构体类型,再定义变量 ```c struct Student { char name[50]; int age; float score; }; struct Student stu1, stu2; ``` - 定义结构体类型的同时定义变量 ```c struct Student { char name[50]; int age; float score; } stu1, stu2; ``` - 定义匿名结构体类型并同时定义变量 ```c struct { char name[50]; int age; float score; } stu1, stu2; ``` ### 结构体的初始化 结构的初始化方式和数组的初始化方式很相似。一个位于一对花括号内部、由逗号分隔的初始值列表可用于结构各个成员的初始化。这些值根据结构成员列表的顺序写出。如果初始列表的值不够,剩余的结构成员将使用缺省值进行初始化[^4]。 ```c struct Student { char name[50]; int age; float score; }; struct Student stu = {"Tom", 20, 85.5}; ``` ### 结构体设计的小建议 在设计结构体的时候,既要满足对齐,又要节省空间,让占用空间小的成员尽量集中在一起。例如: ```c #include <stdio.h> struct p1 { char x; char y; int z; }; struct p2 { char a; int b; char c; }; int main() { int j = sizeof(struct p1); int k = sizeof(struct p2); printf("%d %d", j, k); return 0; } ``` ### 匿名结构体指针 可以创建匿名结构体指针,例如: ```c struct { int b; char c; float d; } a; struct { int b; char c; float d; } *p; // 创建了一个匿名结构体指针(指向这个匿名结构体) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值