本文介绍了如何在C中制作成对列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要删除此代码中的重复项:

I want to remove the repetition in this code:

printf( "%.2f: %s\n",  440.00f, "A4" );
printf( "%.2f: %s\n",  523.25f, "C5" );
printf( "%.2f: %s\n",  880.00f, "A5" );
printf( "%.2f: %s\n", 1046.50f, "C6" );

我的计划是制作一个配对列表并在其上循环.有可能并且是一个好的解决方案,还是我应该只制造两个数组?

My plan is to make a list of pairs and loop over it. Is it possible and a good solution, or should I just make two arrays?

推荐答案

只需创建一个结构数组:

Just make an array of structs:

struct pair {
    double num;
    char str[32];
};

struct pair pairs[10] = {
    {440.00f, "A4"},
    {523.25f, "C5"},
    /* ... */
};

/* C99. */
pairs[2] = (struct pair){880.00f, "A5"};
pairs[3] = (struct pair){
    .str = "C6",
    .num = 1046.50f
};

for (i = 0; i < sizeof(pairs) / sizeof(pairs[0]); i++)
    printf("%.2f: %s\n",  pairs[i].num, pairs[i].str);

这篇关于如何在C中制作成对列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 15:50