注册 登录
编程论坛 C++教室

为什么结果是随机数,给位大神求教

s524250262 发布于 2015-05-27 11:49, 623 次点击
#include <stdio.h>
int main()
{
    int moth,day,year,n,s=0,i;
    printf("请输出年月日:");
    scanf("%d%d%d",&year,&n,&i);
    moth=n;
      do
      {
      switch(moth)
      {
           case 1:
           case 3:
           case 5:
           case 7:
           case 8:
           case 10:
           case 12:day=31; break;
           case 4:
           case 6:
           case 9:
           case 11:day=30;break;
               
      }
      s+=day;
          moth--;
      }while(moth>0);
      s=s-31;//switch上面没有2,系统默认给了day=31的列式。
     if((year%4==0&&year%100!=0)||(year%400==0))//判断年是闰年
          s=s+29;
     else
          s=s+28;
      day=s+i;

          printf("%d\n",day);
          return 0;
}
9 回复
#2
rjsp2015-05-27 12:13
不知所云
你输入什么,输出什么,期待输出什么?
#3
rjsp2015-05-27 12:43
#include <stdio.h>
#include <stdbool.h>

inline bool isleap( unsigned year )
{
    return (year%400==0) || (year%4==0 && year%100!=0);
}

inline unsigned dayofmonth( unsigned year, unsigned month )
{
    static const unsigned dm[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    return dm[month-1] + (month==2 && isleap(year));
}

inline unsigned dayofyear( unsigned year, unsigned month, unsigned day )
{
    static const unsigned dm[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
    return dm[month-1] + day + (month>2 && isleap(year));
}

int main( void )
{
    unsigned year, month, day;
    if( 3==scanf("%u%u%u",&year,&month,&day) && month>=1 && month<=12 && day>=1 && day<=dayofmonth(year,month) )
    {
        printf( "%u\n", dayofyear(year,month,day) );
    }

    return 0;
}
#4
wmf20142015-05-27 13:26
回复 3楼 rjsp
隐形药水?
#5
s5242502622015-05-27 15:09
回复 2楼 rjsp
比如我输入2014,2,5//年月日
然后求它的这一年中到2月5日一共多少天
#6
rjsp2015-05-27 15:21
回复 5楼 s524250262
首先,你不应该输入“2014,2,5”,而应该输入“2014 2 5”,看你自己的代码 scanf("%d%d%d",&year,&n,&i);

第二,当moth等于2时,执行到 s+=day; 这一句的时候,day 根本没有被赋值,这种行为在C/C++中是“未定义行为”
#7
s5242502622015-05-27 15:24
问题解决了,谢谢
#8
s5242502622015-05-27 15:25
回复 6楼 rjsp
谢谢,好感动啊@_@~~
#9
取名字2015-05-27 15:30
且循环之后“s=s-31”也不合理。
#10
yangfrancis2015-05-27 21:33
注意哦,在进入循环之前就应该把月份减1
1