增加函数中的案例编号?

时间:2014-01-01 13:31:14

标签: c switch-statement

我只是在学习C而我在使用同一个printf函数的代码增加dayName时遇到了麻烦。

这是我的代码:

#include <stdio.h>
#define LENGH_OF_WEEK 7

int main()
{
    int daysOfWeek[LENGH_OF_WEEK] = {0,1,2,3,4,5,6};
    char* dayName = NULL;

int i;
for (i = 0; i < LENGH_OF_WEEK; i++)
{
    switch (daysOfWeek[i])
    {
    case 0: dayName = "Sunday"; break;
    case 1: dayName = "Monday"; break;
    case 2: dayName = "Tuesday"; break;
    case 3: dayName = "Wednesday"; break;
    case 4: dayName = "Thursday"; break;
    case 5: dayName = "Friday"; break;
    case 6: dayName = "Saturday"; break;
    }

    printf("%s, %s Happy Days\n", dayName, dayName);
}

return 0;
}

正如你所看到的,我正试图让我的控制台唱出Happy Days,但它只是说dayName两次,我想弄清楚如何让它说“星期六,一天!Groovin'所有和你在一起!“案例6。

5 个答案:

答案 0 :(得分:2)

实用主义者对你的具体问题的回答可能只有6或7个完整的字符串,每天一个(“星期日,星期一快乐日”,“星期一,星期二快乐日”等)。

但是,正如您实际上只是在尝试一样,如果您将索引到日期名称的映射转换为单独的函数:

const char* MapIndexToDayName(int dayIndex)
{
    switch(dayIndex)
    {
    case 0: 
        return "Sunday";
   ... etc.
    }
}

然后你可以更容易地看到你如何拥有一个printf,你传递调用这个函数的结果,包括'today'和'today + 1'

如果你有星期六的特殊情况,那么只需添加'if'来测试当天并单独处理特殊情况,或者在一周的早期部分运行循环,并添加一秒循环结束后,printf应对最后一天。

答案 1 :(得分:2)

这是我的经典主题曲的版本。不使用switch语句,抱歉

#include <stdio.h>


char *day[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int main()
{

int i;
for (i = 0; i < 5; i+=2)
{
    printf("%s, %s Happy Days\n", day[i], day[i+1]);
}
printf("Saturday, what a day\n Groovin' all week with you!\n");

return 0;
}

答案 2 :(得分:1)

我认为你的代码结构还有很多不足之处。

我根本不理解daysOfWeek数组的意思,它只是将0映射到0,1到1,依此类推。

也许你应该使用这样的东西:

typedef enum {
  DAY_MONDAY = 0,
  DAY_TUESDAY,
  DAY_WEDNESDAY,
  DAY_THURSDAY,
  DAY_FRIDAY,
  DAY_SATURDAY,
  DAY_SUNDAY
} DayOfWeek;

然后写一个函数给你每天的名字:

const char * name_of_day(DayOfWeek day)
{
  switch(day)
  {
  case DAY_MONDAY:
    return "Monday";
  case DAY_TUESDAY:
    return "Tuesday";
  /* and so on */
  }
}

然后再次尝试制定打印歌词的程序,但使用DayOfWeek值表示星期几,并使用name_of_day()函数为您提供此类值的字符串表示。

答案 3 :(得分:1)

如果你想获得你想要的东西,最好定义一个字符串数组(换句话说,二维字符数组)并循环并访问该数组中的日期名称。如果您想要一个更接近您的代码的更简单的方法,下面的代码可以工作。

for (i = 0; i < LENGH_OF_WEEK; i+=2)
{
    switch (daysOfWeek[i])
    {
       case 0: string = "Sunday, Monday"; break;
       case 2: string = "Tuesday, Wednesday"; break;
       case 4: string = "Thursday, Friday"; break;
    }

    printf("%s, Happy Days.\n", string);
}

printf("Saturday, What a day, \n Groovin' all week with you. \n", string);

答案 4 :(得分:1)

    char *WeekdayName[] = {
        "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
    char** dayName = WeekdayName;
    int i;
    for (i = 0; i < LENGH_OF_WEEK; i++) {
        printf("%s, ", *dayName++);
        if(i!=6)
            printf("%s Happy Days\n", *dayName);
        else
            printf("what a day! Groovin' all week with you!\n");
    }