现在的位置: 首页 > 综合 > 正文

语言学习1:日期显示,C

2013年10月03日 ⁄ 综合 ⁄ 共 1338字 ⁄ 字号 评论关闭

编写一个函数,要求输入年月日时分秒,输出该年月日时分秒的下一秒。如输入 2004 年 12 月 31 日 23  时59 分 59 秒,则输出 2005 年 1 月 1 日 0 时 0 分 0 秒。

//year.month.day.hour.minute.second

#include <stdio.h>

void Nexttime(int *year,int *month, int *data,int *hour,int *minute,int *second)
{
 int day;
 (*second)++;//秒加1
 if (*second >= 60)//60S后,分钟加1,秒归零
 {
  *second=0;
  (*minute) ++;
  if (*minute >= 60)//60分钟后,小时加1,分钟归零
  {
   *minute=0;
   (*hour)++;
   if (*hour>=24)//24小时后,日期加1,小时归零
   {
    *hour = 0;
    (*data)++; 
 

  //判断每月的天数
   switch(*month)
   {

//31天的月数
   case 1:
   case 3:
   case 5:
   case 7:
   case 8:
   case 10:
   case 12:
    day=31;
    break;

//2月的天数,闰年28天,其余29天
   case 2:
    if (*year %400 ==0 && *year % 100 !=0
     && *year % 4 ==0)//判断闰年
    {
     day=29;
    }
    else
    {
     day=28;
    }
    break;

//剩下的30天
   default:
    day=30;
    break;
   }
   if (*data>day) //如果*data++比上面计算的day数值大,则月份加1,且日期归零
   {
    *data=1;
    (*month)++;
    if(*month>12)//12月后,年份加一,月份归零
    {
     *month=1;
     (*year)++;
    }
   }
  }
 }
}
}

//主函数
void main()
{
int year,month,data,hour,minute,second;
 printf("please input the time:");
 scanf("%d %d %d %d %d %d",&year,&month,&data,&hour,&minute,&second);
 Nexttime(&year,&month,&data,&hour,&minute,&second);
 printf("The result:%d-%d-%d %d:%d:%d",year,month,data,hour,minute,second);}

 

最大的错误是没有认清:* 的运算级比 ++ 小,所以开始出来时一直都是原值。

其次,用scanf()来录入时间,函数的写法要注意

不知道在C++中,如果用iostream.h库函数输入输出怎么写?(cin<<year<<month<<data<<hour<<minute<<second;这样可以吗?还是要用cin.get()函数呢?求解)

抱歉!评论已关闭.