C++Primer Plus P24 编程题四(编写程序,实现秒转天,小时,分钟,秒)——中职

C++Primer Plus P24 编程题四

编写一个程序,要求用户以整数输入秒数(使用long或longlong变量存储),然后以天、小时、分钟和秒显示这段时间。使用符号常量来表示每天有多少小时、
每小时有多少分钟以及每分钟有多少秒。该程序的输出应与下面类似。

Enter the number of seconds:31600000
31600000 seconds = 365 days, 17 hours, 46minutes, 40 seconds.

/*
C++Primer Plus P24 编程题四

编写一个程序,要求用户以整数输入秒数(使用long或longlong变量存储),然后以天、小时、分钟和秒显示这段时间。使用符号常量来表示每天有多少小时、
每小时有多少分钟以及每分钟有多少秒。该程序的输出应与下面类似。

Enter the number of seconds:31600000
31600000 seconds = 365 days, 17 hours, 46minutes, 40 seconds.
*/

//头文件
#include<iostream>

//转换因子(符号常量)
const long seconds_to_min = 60;									//秒转分的转换因子
const long minutes_to_hour = 60;								//分转小时的转换因子
const long hours_to_day = 24;									//小时转天的转换因子

//主函数
int main(void)
{
    
    
	using namespace std;										//编译指令
	long seconds, minutes, hours, days;

	cout << "Enter the number of seconds:";						//显示提醒用户输入秒数
	cin >> seconds;												//秒数

	minutes = seconds / seconds_to_min;							//秒转分
	hours = minutes / minutes_to_hour;							//分转小时
	days = hours / hours_to_day;								//小时转天

	hours = hours % hours_to_day;								//计算几天几小时几分几秒的小时
	minutes = minutes % minutes_to_hour;						//计算几天几小时几分几秒的分
	seconds = seconds % seconds_to_min;							//计算几天几小时几分几秒的秒

	cout << seconds << " seconds = "							//输出总秒数
		<< days << " days, "									//输出几天几小时几分几秒的天
		<< hours << " hours, "									//输出几天几小时几分几秒的小时
		<< minutes << " minutes, "								//输出几天几小时几分几秒的分钟
		<< seconds << " seconds."								//输出几天几小时几分几秒的秒数
		<< endl;												//换行

	return 0;
}

算法简述:
其中的转换因子:

//转换因子(符号常量)
	const long seconds_to_min = 60;									//秒转分的转换因子
	const long minutes_to_hour = 60;								//分转小时的转换因子
	const long hours_to_day = 24;									//小时转天的转换因子

先将其秒依次转换成对应的分钟、小时、天数

	minutes = seconds / seconds_to_min;							//秒转分
	hours = minutes / minutes_to_hour;							//分转小时
	days = hours / hours_to_day;								//小时转天

在将其依次对转换因子取余,计算出剩余的天数

	hours = hours % hours_to_day;								//计算几天几小时几分几秒的小时
	minutes = minutes % minutes_to_hour;						//计算几天几小时几分几秒的分
	seconds = seconds % seconds_to_min;							//计算几天几小时几分几秒的秒

即可,以下是输出结果:

Enter the number of seconds:31600000
40 seconds = 365 days, 17 hours, 46 minutes, 40 seconds.

感谢观看

再次感谢~

猜你喜欢

转载自blog.csdn.net/qq_51212951/article/details/113587567