我必须编写一个程序,用户使用两个整数a和b,其中a对应于一年中的月份(1 = jan,2 = feb等).该程序必须打印"a"和随后的"b"月份之后的月份.这就是我到目前为止所做的,但是对于我输入的每两个整数,我总是得到相同的输出:"1月,2月".任何帮助表示赞赏.
#include<stdio.h>
enum month {jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec}; /*This
allows yoou to name a finite set and to declare identifiers*/
typedef enum month month;
month next_month(month M) /*this is a function definition*/
{
switch (M) /* like an if-else statement, if this month is true goto the M=month you chose*/
{
case jan:
M=feb;break;
case feb:
M=mar;break;
case mar:
M=apr;break;
case apr:
M=may;break;
case may:
M=jun;break;
case jun:
M=jul;break;
case jul:
M=aug;break;
case aug:
M=sep;break;
case sep:
M=oct;break;
case oct:
M=nov;break;
case nov:
M=dec;break;
case dec:
M=jan;break;
}
return M;
}
void print_month (month M) /*this is a function definition*/
{
switch (M) /* like an if-else statement, if this month is true goto the M=month you chose*/
{
case jan:
printf("January");break;
case feb:
printf("February");break;
case mar:
printf("March");break;
case apr:
printf("April");break;
case may:
printf("May");break;
case jun:
printf("June");break;
case jul:
printf("July");break;
case aug:
printf("August");break;
case sep:
printf("September");break;
case oct:
printf("October");break;
case nov:
printf("November");break;
case dec:
printf("December");break;
}
}
int main(void)
{
month M, N, sat;
printf("Please enter two integers:\n");
scanf("%d%d", &M, &N);
for (M = jan; M <= N; ((int)M++))
{
printf(" ");
print_month(M); /*function call to print month*/
printf(" ");
print_month(next_month(M)); /*function call to print previous month*/
putchar('\n');
return;
}
}
Run Code Online (Sandbox Code Playgroud)
你有这个主要的
scanf("%d%d", &M, &N);
for (M = jan; M <= N; ((int)M++))
{
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
因此......在scanf行中,您将M(和N)更改为用户提供的值,
然后将M设置为jan有效地丢失用户选择的值.
你需要检查你的方式.
我对改进程序的建议是将switch语句替换为月份名称数组.编程和阅读会容易得多.
每当您可以用数据结构替换代码时,这通常是一个很大的改进.无论何时进行编程,这都需要记住和使用.
所以按照我的建议使用月份数组看起来有点像这样:
#include <stdio.h>
const char* months[12] = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
int main(void)
{
int m;
printf("Enter month: ");
scanf("%d", &m);
if( 1 <= m && m <= 12 ) {
printf("%s\n", months[m-1]);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6746 次 |
| 最近记录: |