全WA但很多数据都通过了,求指导!

P5707 【深基2.例12】上学迟到

PBtolimits @ 2024-11-14 11:52:05

用字符数组写为什么全WA呀?求教!

#include <stdio.h>
int main()
{
    int s,v,tr,hour,minute,dh,dm;
    int h=7,m=50;
    scanf("%d %d",&s,&v);

    if(s%v==0){
        tr=s/v;
        hour=tr/60;
        minute=tr%60;
    }
    else{
        tr=s/v+1;
        hour=tr/60;
        minute=tr%60;
    }
    if(m-minute<0){
        h--;
        m+=60;
    }
    dm=m-minute;

    if(h-hour<0){
        h+=24;
    }
    dh=h-hour;

    char dp[5];
    dp[2]=':';

    if(dm==0){
        dp[3]='0';
        dp[4]='0';
    }
    if(dm<10){
        dp[3]='0';
        dp[4]='0'+dm;
    }
    if(dm>=10){
        dp[3]=(dm/10)+'0';
        dp[4]=(dm%10)+'0';
    }   

    if(dh==0){
        dp[0]='0';
        dp[1]='0';
    }

    if(dh<10){
        dp[0]='0';
        dp[1]=dh+'0';
    }
    if(dh>=10){
        dp[0]=(dh/10)+'0';
        dp[1]=(dh%10)+'0';
    }

    printf("%s",dp);

    return 0;
}

by complete_binary_tree @ 2024-11-14 11:59:24

字符数组开小了,应该开 char dp[6],最后一位要存 \0,否则会 UB。


by PBtolimits @ 2024-11-14 12:52:07

@complete_binary_tree AC了,感谢感谢!


|