相互关联的打印数组和枚举C [英] printing arrays and enums in relation to each other C
问题描述
我正在尝试打印与 Numbers
数组有关的枚举 Months
.我正在尝试使用该关系格式化打印功能
I am trying to print the enums Months
in relation to the Numbers
array. I am trying to format the print function with the relation
#include <stdio.h>
int main ()
{
Numbers[12] = {3,4,5,1,2,7,8,9,3,4,7,8};
enum Months {Jan, Feb, March, April, May, June, July, August, September, October, November, December};
for(int i = 0; i> 12; i ++){
printf("Month: %d Number: %d", Months[i], Numbers[i]);
}
return 0;
}
预期输出:
Jan: 3
Feb: 4
March: 5
April: 1
May: 2
June: 7
July: 8
August: 9
September: 3
October: 4
November: 7
December: 8
推荐答案
首先,必须使用数据类型定义数组.我认为它是整数.
Firstly, the array must be defined with a data type. I assume it is integer.
另一个主要问题是枚举不是字符串.它们用于为常量设置有意义的名称,例如 enum {OPTION1,OPTION2,OPTION3}
,以减少使用幻数.因此,我们需要使用字符数组来存储月份的名称.
Another major issue is that the enums are not strings. They are used to set meaningful names for constants such as enum {OPTION1, OPTION2, OPTION3}
to reduce the usage of magical numbers. Thus, we need to use a character array to store the name of the months.
最后,语义问题是 i>12
在循环中–这不会让循环被执行.相反,条件应为 i<12
.
Lastly, a semantic issue is i > 12
in the loop – this won't let the loop be executed. Instead, the condition should be i < 12
.
修饰的代码应如下所示:
The polished code should look like this:
#include <stdio.h>
#define MAX_LEN 32
int main() {
int Numbers[12] = {3, 4, 5, 1, 2, 7, 8, 9, 3, 4, 7, 8};
char Months[][MAX_LEN] = {"Jan", "Feb", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"};
for (int i = 0; i < 12; i++)
printf("%s: %d\n", Months[i], Numbers[i]);
return 0;
}
这样您将获得正确的输出:
So you get the correct output:
rohanbari@genesis:~/stack$ ./a.out
Jan: 3
Feb: 4
March: 5
April: 1
May: 2
June: 7
July: 8
August: 9
September: 3
October: 4
November: 7
December: 8
这篇关于相互关联的打印数组和枚举C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!