我编写了以下控制台应用程序,要求用户输入日期。

我需要一些帮助以进行改进,以便他们在一周的所有天中都能给出正确的答案。

如果用户输入除星期一以外的任何其他日期,则输出为“今天”,“昨天”,“明天”,并且相应日期输出在这些标题下方。

问题似乎只是星期一没有产生正确的输出。

到目前为止,这是我的代码:

#include "stdafx.h"
#include <stdio.h>
#include <string.h>

typedef enum  the_days {monday,tuesday,wednesday,thursday,friday,saturday,sunday, noday} day;

day yesterday (day today);
day tomorrow (day today);

char thedays[][10] = {"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"};

day findDay(char string1[]);

void main(void)
{
    day today;
    char theDay[10];

    puts("Type the day (e.g. 'monday'");
    gets(theDay);

    today = findDay(theDay);

    if(today == noday)
    {
        puts("Error - invalid input - exiting");
        return;
    }

    printf("today    \tyesterday  \ttomorrow\n"
        "============================================\n");
    printf("%s\t %s \t %s\n", thedays[today],   thedays[yesterday(today)],thedays[tomorrow(today)]);
}

day findDay(char string1[])
{
    int i = 0;
    day thisday;

    for (i=0;i<7;i++)
    {
        if (!strcmp(thedays[i],string1))
        {
            break;
        }
    }
    thisday = (day)i;
    return thisday;
}

day yesterday(day today)
{
    day before;
    before = (day)(today- 1);
    return before;
}

day tomorrow(day today)
{
    day after;
    after = (day)(today + 1);
    return after;
}

最佳答案

您将在星期一和星期日获得不正确的结果,因为您的yesterdaytomorrow函数没有处理所有回绕。您可以像这样修复这些功能:

day yesterday(day today)
{
    day before = today > monday ? today - 1 : sunday;
    return before;
}

day tomorrow(day today)
{
    day after = today < sunday ? today + 1 : monday;
    return after;
}

关于c - 增强2种功能以提供正确的输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26868259/

10-11 19:01