gpt4 book ai didi

c - 增强 2 个函数以提供正确的输出

转载 作者:行者123 更新时间:2023-11-30 21:25:48 27 4
gpt4 key购买 nike

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

我需要一些帮助才能改进,以便他们为一周中的所有日子提供正确的答案。

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

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

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

#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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com