c - 函数中的 12 天圣诞节 C 程序

标签 c

一个 C 程序,包含输出传统圣诞歌曲“圣诞节十二天”歌词的函数。不要手动打印整个歌词。

所以我编写了一个代码,但出现了错误,但我最终修复了它。我的十二天圣诞歌曲循环打印效果很好。

但是我还有一个问题。我的代码是否可以作为函数分离或剖析?

指令说,“你的函数只会在 main() 函数中被调用,不会返回任何东西。”所以我想我会使用 void?以什么方式?

#include <stdio.h>
#include <conio.h>

int main() // Main Function
{
int days, counter, num;

printf("\n\t\t* * * TWELVE DAYS OF CHRISTMAS * * *\n");
printf("\t\t_____________________________________\n\n\n");

for (counter=1; counter<=12; counter++) {

printf("\tOn the ");

switch(counter){
        case 1:
            printf("1st");
            break;
        case 2:
            printf("2nd");
            break;
        case 3:
            printf("3rd");
            break;
        default:
            printf("%dth", counter);
            break;
    }
printf(" day of Christmas my true love sent to me\n\n");

switch(counter) {

    case 12: printf("\t\tTwelve Drummers Drumming\n\n");
    case 11: printf("\t\tEleven Pipers Piping\n\n"); 
    case 10: printf("\t\tTen Lords a Leaping\n\n");
    case 9: printf("\t\tNine Ladies Dancing\n\n"); 
    case 8: printf("\t\tEight Maids a Milking\n\n");
    case 7: printf("\t\tSeven Swans a Swimming\n\n");
    case 6: printf("\t\tSix Geese a Laying\n\n"); 
    case 5: printf("\t\tFive Golden Rings\n\n"); 
    case 4: printf("\t\tFour Calling Birds \n\n"); 
    case 3: printf("\t\tThree French Hens\n\n");
    case 2: printf("\t\tTwo Turtle Doves\n\n");
    case 1: printf("\t\t");if (counter > 1 ) printf("And ");printf("A Partridge in a Pear Tree\n\n");
    //  case 1: printf("\t\tA Partridge in a Pear Tree\n\n");



}

}

getchar(); return 0; }

尝试执行此操作并且可以正常打印。您对改进我的代码有什么建议吗?函数有问题。

最佳答案

这只是意味着所有的工作都应该在一个 void 函数中完成,然后在 main 中调用它:

void doTheWork(void); // function declaration

int main(void)
{
  doTheWork();
  return 0;
}

#include <stdio.h>
// function definition
void doTheWork(void)
{
  // put the implementation here
}

关于c - 函数中的 12 天圣诞节 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18460730/

相关文章:

c - 使用类对象宏是定义全局变量的好方法吗?

c - 为什么宏定义 "#define yyparse ol_parser_parse"可以工作?

c 表达式求值器 take 2

c - 如何用 C 语言从字符串中解析 IP 地址?

c++ - 似乎无法获得一个 char 数组来离开函数并在 main 中可用

c - 如何将长无符号转换为无符号char *?

计算具有给定除数的正整数

c - c 中的管道消息被截断

C、前后自增,不同程序答案不同

c++ - 如何删除输入的字母/字符串或任何输入