【C/C++】如何计算两个日期相差多少天

c++程序 计算两个日期相差的天数  #include #include #include using namespace std; struct Date{  int y;//year  int m;//month  int d;//day in month }; int isLeap(int y) {  return y%4==0 && y%100==0 || y%400==0; } int 阅读详情
AI摘要

本文详细介绍了如何编写程序计算给定日期距公元元年的天数,判断日期合法性,并计算两个日期之间的天数差。涉及闰年判断、月份天数计算和基姆拉尔森公式应用。

一、计算某一日期距公元元年多少天

首先先写一个程序判断闰年,如果是400的倍数或可以被4整除又不是100的倍数的都是闰年,例如2000年就是闰年,而1900年不是闰年

代码如下:

bool choose(long long year) {
	if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
		return true;
	return false;
}

如果是闰年,则返回真,否则返回假

我们知道平年有365天,闰年有366天,而一年有12个月,大月31天,小月30天,2月要看是否为闰年,则年的天数为:

我们先定义一个自定义函数:

long long day(long long Year, long long Month, long long Day) {
	long long day = 1;
}

其中

long long day = 1;

为储存所有天数的变量

则年天数为:

for (long long i = 1; i < Year; i++) {
		bool year = choose(i);
		if (year)
			day += 366;
		if (!year)
			day += 365;
	}

月天数为:

for (long long i = 1; i < Month; i++) {
		if (i == 2) {
			if (choose(Year))
				day += 29;
			else if (!choose(Year))
				day += 28;
		} else if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)
			day += 31;
		else if (i == 4 || i == 6 || i == 9 || i == 11)
			day += 30;
	}

最后天数直接加起来,就可以得到总天数

 

Main函数:

int main()
{
    long long Year, Month, Day;
	cout << "请输入时间(按照1 1 1格式输入):" ;
	cin >> Year >> Month >> Day;
	long long days = day(Year, Month, Day);
	cout << "距公元元年";
	cout << days;
	cout << "天";
	return 0;
}

但做到这里还不够,如果输入2300 13 90,那么就会出错,所以我们还需要加入一个判断程序,判断日期是否具有合法性,不需要判断年,代码如下:

bool legitimacy(long long year, long long month, long long day) {
	if (month < 1 || month > 12 || day < 1 || day > 31)
		return false;
	else if (month == 2||month == 0) {
		if (choose(year) && day > 29 || !choose(year) && day > 28)
			return false;
	}
	else if (day == 0)
		return false;
	return true;
}

如果合法则返回真,反之返回假

同时Main函数也需进行变动,加入:

bool flag = false;
if (!legitimacy(Year, Month, Day)) {
		while (!flag) {
			cout << "输入错误,请输入时间(按照1 1 1格式输入):" ;
			cin >> Year >> Month >> Day;
			flag = legitimacy(Year, Month, Day);
		}
	}

完整代码如下:

#include <iostream>
#include <windows.h>
using namespace std;

bool choose(long long year) {
	if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
		return true;
	return false;
}

bool legitimacy(long long year, long long month, long long day) {
	if (month < 1 || month > 12 || day < 1 || day > 31)
		return false;
	else if (month == 2) {
		if (choose(year) && day > 29 || !choose(year) && day > 28)
			return false;
	}
	return true;
}

long long day(long long Year, long long Month, long long Day) {
	long long day = 1;
	for (long long i = 1; i < Year; i++) {
		bool year = choose(i);
		if (year)
			day += 366;
		if (!year)
			day += 365;
	}
	for (long long i = 1; i < Month; i++) {
		if (i == 2) {
			if (choose(Year))
				day += 29;
			else if (!choose(Year))
				day += 28;
		} else if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)
			day += 31;
		else if (i == 4 || i == 6 || i == 9 || i == 11)
			day += 30;
	}
	day += Day;
	return day;
}

int week(long long Year, long long Month, long long Day) {
    if(Month == 1 || Month == 2) {
        Month += 12;
        Year--;
    }
    int week = (Day + 2 * Month +3 * (Month + 1) / 5 + Year + Year / 4 - Year / 100 + Year / 400) % 7 + 1;
    return week;
}

int main() {
	system("color a");
	long long Year, Month, Day;
	bool flag = false;
	cout << "请输入时间(按照1 1 1格式输入):" ;
	cin >> Year >> Month >> Day;
	if (!legitimacy(Year, Month, Day)) {
		while (!flag) {
			cout << "输入错误,请输入时间(按照1 1 1格式输入):" ;
			cin >> Year >> Month >> Day;
			flag = legitimacy(Year, Month, Day);
		}
	}
	long long days = day(Year, Month, Day);
	cout << "距公元元年";
	cout << days;
	cout << "天";
	return 0;
}

此外,我们还可以加入判断周几的程序,运用基姆拉尔森计算公式

注意:这个公式需要把一月和二月看成是上一年的十三月和十四月,例:如果是 2004 1 10 则换算成:2003 13 10来代入公式计算

string Week[7]={"一", "二", "三", "四", "五", "六", "日"};
int week(long long Year, long long Month, long long Day) {
    if(Month == 1 || Month == 2) {
        Month += 12;
        Year--;
    }
    int week = (Day + 2 * Month +3 * (Month + 1) / 5 + Year + Year / 4 - Year / 100 + Year / 400) % 7 + 1;
    return week;
}

因为返回的是数字,所以定义Week数组来转成中文,Main函数也需变动,不过多展示

改进后代码如下:

#include <iostream>
#include <windows.h>
using namespace std;

string Week[7]={"一", "二", "三", "四", "五", "六", "日"};

bool choose(long long year) {
	if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
		return true;
	return false;
}

bool legitimacy(long long year, long long month, long long day) {
	if (month < 1 || month > 12 || day < 1 || day > 31)
		return false;
	else if (month == 2) {
		if (choose(year) && day > 29 || !choose(year) && day > 28)
			return false;
	}
	return true;
}

long long day(long long Year, long long Month, long long Day) {
	long long day = 1;
	for (long long i = 1; i < Year; i++) {
		bool year = choose(i);
		if (year)
			day += 366;
		if (!year)
			day += 365;
	}
	for (long long i = 1; i < Month; i++) {
		if (i == 2) {
			if (choose(Year))
				day += 29;
			else if (!choose(Year))
				day += 28;
		} else if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)
			day += 31;
		else if (i == 4 || i == 6 || i == 9 || i == 11)
			day += 30;
	}
	day += Day;
	return day;
}

int week(long long Year, long long Month, long long Day) {
    if(Month == 1 || Month == 2) {
        Month += 12;
        Year--;
    }
    int week = (Day + 2 * Month +3 * (Month + 1) / 5 + Year + Year / 4 - Year / 100 + Year / 400) % 7 + 1;
    return week;
}

int main() {
	system("color a");
	long long Year, Month, Day;
	bool flag = false;
	cout << "请输入时间(按照1 1 1格式输入):" ;
	cin >> Year >> Month >> Day;
	if (!legitimacy(Year, Month, Day)) {
		while (!flag) {
			cout << "输入错误,请输入时间(按照1 1 1格式输入):" ;
			cin >> Year >> Month >> Day;
			flag = legitimacy(Year, Month, Day);
		}
	}
	long long days = day(Year, Month, Day);
	int WEEK = week(Year, Month, Day);
	cout << "距公元元年";
	cout << days;
	cout << "天";
	cout << " ";
	cout << "周";
	cout << Week[WEEK - 1];
	return 0;
}

二、计算两个日期的天数差

如果要计算两个日期的天数差,只需要将两个日期全部化成天数后相减即可

代码如下:

#include <iostream>
#include <windows.h>
using namespace std;

string Week[7]={"一", "二", "三", "四", "五", "六", "日"};

bool choose(long long year) {
	if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
		return true;
	return false;
}

bool legitimacy(long long year, long long month, long long day) {
	if (month < 1 || month > 12 || day < 1 || day > 31)
		return false;
	else if (month == 2||month == 0) {
		if (choose(year) && day > 29 || !choose(year) && day > 28)
			return false;
	}
	else if (day == 0)
		return false;
	return true;
}

long long day(long long Year, long long Month, long long Day) {
	long long day = 1;
	for (long long i = 1; i < Year; i++) {
		bool year = choose(i);
		if (year)
			day += 366;
		if (!year)
			day += 365;
	}
	for (long long i = 1; i < Month; i++) {
		if (i == 2) {
			if (choose(Year))
				day += 29;
			else if (!choose(Year))
				day += 28;
		} else if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)
			day += 31;
		else if (i == 4 || i == 6 || i == 9 || i == 11)
			day += 30;
	}
	day += Day;
	return day;
}

int week(long long Year, long long Month, long long Day) {
    if(Month == 1 || Month == 2) {
        Month += 12;
        Year--;
    }
    int week = (Day + 2 * Month +3 * (Month + 1) / 5 + Year + Year / 4 - Year / 100 + Year / 400) % 7 + 1;
    return week;
}

int main() {
	system("color a");
	long long Year, Month, Day;
	long long Year_two, Month_two, Day_two;
	bool flag = false;
	bool flag_two = false;
	cout << "请输入两个时间(按照1 1 1格式输入):" ;
	cin >> Year >> Month >> Day;
	cin >> Year_two >> Month_two >> Day_two;
	if (!legitimacy(Year, Month, Day)) {
		while (!flag) {
			cout << "输入错误,请重新输入第一个时间(按照1 1 1格式输入):" ;
			cin >> Year >> Month >> Day;
			flag = legitimacy(Year, Month, Day);
		}
	}
	if (!legitimacy(Year_two, Month_two, Day_two)) {
		while (!flag_two) {
			cout << "输入错误,请重新输入第二个时间(按照1 1 1格式输入):";
			cin >> Year_two >> Month_two >> Day_two;
			flag_two = legitimacy(Year_two, Month_two, Day_two);
		}
	}
	long long days = day(Year, Month, Day);
	long long days_two = day(Year_two, Month_two, Day_two);
	int WEEK = week(Year, Month, Day);
	int WEEK_two = week(Year_two, Month_two, Day_two);
	cout << "第一个日期距公元元年";
	cout << days;
	cout << "天";
	cout << " ";
	cout << "周";
	cout << Week[WEEK - 1] << endl;
	cout << "第二个日期距公元元年";
	cout << days_two;
	cout << "天";
	cout << " ";
	cout << "周";
	cout << Week[WEEK_two - 1] << endl;
	cout << "两个日期相差";
	cout << abs(days - days_two);
	cout << "天";
	return 0;
}

希望对大家有所帮助!

 

 

C++计算任意两个日期的天数差 萌新上路,为了完成这个实验题,摸索了好几天,好不容易调试完成,基本没啥问题了,发出来纪念一下。无论是算法还是语句都还有很多值得改进之处,望各位不吝赐教! 先说一下思路: 1.计算天数差的难点在于闰年,解决闰年问题就基本没问题。 2.大体算法是:计算每个日期到当年年底的天数>计算年与年之间的总天数差(此处认为计算年初到年初或年末到年末都行)>用总天数差加上两个日期到当年年底天数之差即为结... 阅读详情

相关推荐

计算两个日期相差天数的最简洁的代码

因为把闰月挪到了最后一个月,所以 m = 14 时(就是表示 2 月),计算结果只是 3 ~ 13 月的总天数,并不会受闰月影响。计算日期差的算法,无论什么算法(除了故意浪费时间的算法),时间复杂度都是 O(1),这个没什么好说的,关键在于优化计算步骤。该算法先根据年月日求出该日期距离 0001年1月1日 的总天数,然后两个天数直接相减,即可求出相差的天数。天数:31-30-31-30-31;5 个月一组,1-0-1-0-1,重复(先减去 30,好看清楚)。

weixin_58045538的博客 1372

C++ 计算两个日期之间的天数

将日期转换为整数,表示自一个纪元以来的天数,然后减去。在这个例子中,我选择了。

Slayer_Zhao的博客 1757

C++计算两个日期之间的天数

在C++中,我们可以使用日期和时间库来计算两个日期之间的天数。以下是一个示例程序,演示了如何使用C++编写一个函数来计算两个日期之间的天数。函数,该函数接受两个日期的年、月、日作为输入,并返回这两个日期之间的天数。计算两个时间戳之间的时间差。最后,我们将时间差转换为天数,并将结果返回。这是一个简单的C++程序,用于计算两个日期之间的天数。函数中,我们首先通过用户输入获取两个日期的年、月、日。函数计算两个日期之间的天数,并将结果输出到屏幕上。结构体,以便进行日期的设置。C++计算两个日期之间的天数。

CyberNova的博客 686

【C++】计算两个日期之间的差

rt 代码如下 #include<iostream> #include<cmath> #include<algorithm> using namespace std; bool judge(int x) { if((x%4==0&&x%100!=0)||x%400==0) return true; else return false; } int sum(int x1,int x2,int x3,int d1) { switch(x

qq_44343213的博客 1848

C/C++ 两个日期之间的天数算法详解及源码

【代码】C/C++ 两个日期之间的天数算法详解及源码。

希望我的博客,能帮上你解决学习中工作中所遇到的问题 8337

计算两个日期相差的天数(C/C++实现)

然后,函数计算起始日期到所在年底的天数,通过循环遍历起始日期的月份,累加每个月的剩余天数。在第一个月,它只计算起始日期当月的剩余天数,之后的月份都计算整个月的天数。然后,函数计算起始日期到所在年底的天数,通过循环遍历起始日期的月份,累加每个月的剩余天数。在第一个月,它只计算起始日期当月的剩余天数,之后的月份都计算整个月的天数。最后,函数计算结束日期到所在年初的天数,通过循环遍历结束日期的月份,累加每个月的天数。最后,函数计算结束日期到所在年初的天数,通过循环遍历结束日期的月份,累加每个月的天数。

DevForge的博客 565

c/c++ 输入两个日期,计算日期相差多少天

1,题目: 有两个日期,计算它们之间的差值,如果两个日期是连续的,则按照2天算。 日期格式规定为YYYYMMDD,例如20200709 2,基本思路 (1)输入两个日期 (2)以小的日期为底,每次加一天,直到与大的日期相等即可 (2.1)增加一天后,月份,年份都可能会随之变化。针对闰年平年以及大小月天数都一样,采用一个12*2的二维数组列出12月的润平年的天数。 (2.2)当达到月份的天数时,月份加1 (2.3)当达到12个月时,年份加1 3 代码 #include <iostream> #in

编程侯的专栏 9620

基于STM32的智能台灯PWM调光与人体感应融合设计

本文详细介绍了基于STM32单片机的智能台灯设计方案,重点讲解了PWM调光技术与人体感应模块的融合实现。通过STM32的高级定时器产生精准PWM信号控制LED亮度,结合红外传感器实现人来灯亮、人走灯灭的智能体验,同时集成光敏传感实现环境自适应调光,打造高效节能的智能照明解决方案。

threejs5artist的博客 827

cocos2d-x3.3获取时间

一、获取时间 struct tm *tm; time_t timep; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)  time(&timep); #else struct timeval tv; gettimeofday(&tv, NULL); timep = tv.tv_sec; #endif  tm = localtime(&

u012408019的专栏 947

【阿里云大模型高级工程师ACP习题集】2.1 用大模型构建新人答疑机器人

【摘要】这是我精心整理出对应的习题集,里面足足有 30 道题目,从基础概念到深度拓展,全方位覆盖章节重点、难点。不管你是想检验自己的学习成果,还是想针对薄弱环节进行强化训练,它都能完美适配!

davidkorhenn的博客 2614

如何搭建pikachu靶场

Pikachu靶场本地搭建指南 下载安装PHPStudy并启动Apache/MySQL服务 获取Pikachu靶场源码并解压到网站根目录 配置数据库连接信息(修改config.inc.php文件) 创建pikachu数据库(用户名/密码设为root) 访问http://localhost/pikachu测试功能 常见问题:数据库连接失败需检查服务状态和配置信息,页面报错需检查PHP版本兼容性。建议使用PHP7.3/7.4版本,在隔离环境中搭建使用。 (150字)

2401_85351702的博客 1284

计算两个日期之间,相差多少天C语言详解

问题描述:如2019-12-27与2017-11-7,相差780天。 编译环境:vc++6.0 代码: #include <stdio.h> /*计算两个日期之间相差多少天*/ struct date { int years; int months; int days; }; int days_on_month[13] = { 0,31,28,31,30,31,30,31,3...

学习笔记,仅供参考 1万+

洛奇 服务器文件,MabinogiG20S2 [洛奇G20服务端]

Code:Titles:>set_title /id: /add /remove Parameters for titles>set_title /id:60001 /add add devcat title>set_title /id:60001 /remove remove devcat title===========================...

weixin_30813385的博客 4316

(C++)设计一个日期类Date,包括年、月、日等私有数据成员。要求实现日期的基本运算,包括某日期加上指定天数、某日期减去指定天数、两个日期相差的天数等。

C++面向对象程序设计课后作业第239页第5题 题目要求:设计一个日期类Date,包括年、月、日等私有数据成员。要求实现日期的基本运算,包括某日期加上指定天数、某日期减去指定天数、两个日期相差的天数等。 代码仅供参考 #include<iostream> #include<math.h> using namespace std; class Date { private: int year; //年份 int month; //月份 int day; //天

qq_44620333的博客 1万+

Python量化交易:计算累积收益率

可以使用第三方库(例如pandas_datareader)从各大金融数据源获取股票的历史价格数据,或者使用自己的数据源。通过计算累积收益率,我们可以了解投资的整体盈利情况,并对投资策略进行评估和调整。在量化交易中,计算累积收益率是一项重要的任务。累积收益率反映了投资组合或某个股票的整体收益情况,能够帮助我们评估投资的盈利能力。本文将介绍如何使用Python计算累积收益率,并提供相应的源代码。在计算每日收益率之后,我们可以计算累积收益率。最后,我们可以绘制累积收益率的曲线图,以直观地观察投资的收益情况。

CodeHeroicX的博客 811

从 Junior 到 Lead:ABAP 开发者进阶路线图与真实项目练级法

本文拆解了ABAP工程师从初级到高级的成长路径,强调能力提升依赖于可复用经验的积累。对于初级开发者,建议夯实ABAP Dictionary、内表处理和数据库思维三大基础,培养数据流与规则层的结构化思维,并逐步掌握面向对象编程。中级阶段应注重代码可维护性,通过单元测试和Clean ABAP规范提升工程质量。文章指出,ABAP开发者需要学会筛选学习重点,建立知识地图,并重视团队协作中的代码可读性。关键在于将碎片知识整合为可迁移的模型,而非盲目追求新技术。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 181

C/C++任给两个日期,格式为年-月-日,算出两个日期相差的天数

任给两个日期,格式为年-月-日,算出两个日期相差的天数 描述 给定两个日期,计算相差的天数。比如2010-1-1和2010-1-3相差2天。 输入 共两行: 第一行包含三个整数startYear,startMonth,startDay,分别是起始年、月、日。 第二行包含三个整数endYear,endMonth,endDay,分别是结束年、月、日。 相邻两个整数之间用单个空格隔开。 年份范围在1~3...

weixin_46433162的博客 2430

Apollo Planning2.0决策规划算法代码详细解析 (1):环境搭建

1、官方提供连接:git clone https://github.com/ApolloAuto/application-pnc.git。此外,也更新了dreamview对pnc的支持,使得调试更加方便。apollo开源团队近期更新了planning版本,对代码进行了一定程度上的重构。(2)进入docker,并编译整个工程:./apollo.sh build_dbg。下载项目环境后使用aem进行环境配置;2、有一定基础建议直接拉取最新代码,自己手动进行编译。(1)环境安装: ./dev_start.sh。

自动驾驶Player的博客 1843

输入两个日期(年月日,年月日),输出这两个日期之间差多少天。C语言

//(1)输入年月日,输出该日期是当年的第几天。 //(2)输入两个日期(年月日,年月日), 输出这两个日期之间差多少天。 //两问重复,此处写第二问。 #include<cstdio> //判断是否是闰年 int isLeap(int year){ if(year%4==0&&year%100==0||year%400==0) return 0; else ...

blog 4960

【AI智能体】Dify 基于知识库搭建智能客服问答应用详解

Dify 基于知识库搭建智能客服问答应用详解

congge 6934

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

C语言 实现 计算两个日期之间有多少天

/* count how many day between two dates * ensure the first input date before second date * * input : xxxx xx xx * input : xxxx xx xx */ #include <stdio.h> int isleap(int y...

AFANTI_JK的博客 2185

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

oracler日期函数相差六个月_oracle 计算两个时间之间的月份差,相差几个星期,相差多少天...

相差多少天:sysdate-to_date('1991-01-01','YYYY-MM-DD'))<7 and (sysdate-to_date('1991=01=01','YYYY-MM-DD'))>0相差几个星期用to_char(sysdate,'ww')获取时间为当年的第多少个星期,同理做减法即可获得差值两个时间之间的月份差select substr(to_char(sysda...

weixin_39526238的博客 719

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

计算两个人的出生日期相差的天数

/* * 程序的版权和版本声明部分 * Copyright (c)2013, 烟台大学计算机学院学生 * All rightsreserved. * 文件名称: fibnacci.cpp * 作 者:高古尊 * 完成日期:2014年2月27日 * 版本号: v1.0 * * 输入描述: * 问题描述:计算两个人的出生日期相差的天数 * 程序输出: * 问题分析: *

u012332009的专栏 6134

C/C++语言实现给定日期计算该日期与当前日期的相差天数

#include <stdio.h> #include <time.h> #include<math.h> #define TRUE 1 #define FALSE 0 size_t StringToDatetime(char *str) { time_t ocurtime; char buffer[80]; struct tm tm_; int year, month, day; sscanf(str,"%d-%d-%d", .

qq_39540537的博客 1218

利用Struct计算两个日期的相差的天数

//目的计算两个日期之间相差的天数,并且计算填入的日期当天是星期几 #include "stdafx.h" #include using namespace std; struct Date{ int year; int month;     int day; }; //计算是否为闰年 bool isLeapYear(int year) {    

xxd654321的专栏 606
上一篇: Clion安装教程
下一篇: 最简单免费的MFLAC转换FLAC和MP3的方法
秋天树下的太阳
博客等级 码龄4年 31粉丝 8原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址