如何让它更美丽?

时间:2018-01-11 12:29:38

标签: c refactoring pebble-watch

Pebble手表应用程序的示例代码。 代码在两个时间戳之间工作并输出一个计时器,但如何使它更美观?

char d[5];
char h[5];
char m[5];
char s[5];
const char *start = "START";

time_t now_time = time(NULL);
int tt = other_time - now_time;

if (tt > 0) {
    int rest = tt % 31556926;
    int dd = rest / 86400;
    rest = tt % 86400;
    int hh = rest / 3600;
    rest = tt % 3600;
    int mm = rest / 60;
    int ss = rest % 60;

    if (dd > 0) 
        snprintf(d, sizeof(d), "%dD", dd);
    else
        snprintf(d, sizeof(d), "%s", "\n");
    ...
    if (ss > 0)
        snprintf(s, sizeof(s), " %dS", ss);
    else
        snprintf(s, sizeof(s), "%s", "\n");

    snprintf(string, sizeof(string), "%s%s%s%s", d, h, m, s);  
} else {
    snprintf(string, sizeof(string), "%s", start);
}

1 个答案:

答案 0 :(得分:2)

如果"美丽"你的意思是"优雅" (这通常被视为"简洁有效"),我会尝试类似的事情:

#include <stdio.h>
#include <time.h>

char * getDuration(time_t future)
{
    char * duration = (char *) malloc(sizeof(char) * 32);
    int elapsed = (int) (future - time(NULL));
    if(elapsed > 0)
    {
        int d = (elapsed % 31556926) / 86400;
        int h = (elapsed %    86400) /  3600;
        int m = (elapsed %     3600) /    60;
        int s = (elapsed %       60)        ;
        sprintf(duration, "%sD%sH%sM%sS", d, h, m, s);  
    }
    else sprintf(duration, "START");
    return duration;
}
PS:我没有理解为什么要打印&#34; \ n&#34;在字符串而不是&#34; 0D&#34;,&#34; 0H&#34;等