【发布时间】:2016-05-15 21:32:04
【问题描述】:
在打开 switch case 之前使用 if 语句并避免使用 default 关键字是否正确?
例如,我想要一个程序,它将月份的数字作为输入并告诉你它的名称。这是使用switch case 语句的代码:
#include <stdio.h>
#include <stdlib.h>
main() {
int month;
printf("Insert the number of the month and the program will return its name");
scanf("%i", &month);
switch (month) {
case (1):
printf("The month is January");
break;
case (2):
printf("The month is February");
break;
case (3):
printf("The month is March");
break;
case (4):
printf("The month is April");
break;
case (5):
printf("The month is May");
break;
case (6):
printf("The month is June");
break;
case (7):
printf("The month is July");
break;
case (8):
printf("The month is August");
break;
case (9):
printf("The month is September");
break;
case (10):
printf("The month is October");
break;
case (11):
printf("The month is November");
break;
case (12):
printf("The month is December");
break;
default:
printf("not valid");
}
system("pause");
return 0;
}
然后,我想知道是否可以将无效条件放在 if 语句中,而不是放在 default 关键字中。对我来说这似乎是正确的,因为我想在程序执行 switch case 语句之前验证该值。你怎么看,会是正确的吗?如果我没有问太多,请你告诉我为什么?
带有if语句的代码:
#include <stdio.h>
#include <stdlib.h>
main() {
int month;
printf("Insert the number of the month and the program will return its name");
scanf("%i", &month);
if (month >= 1 && month <= 12) {
switch (month) {
case (1):
printf("The month is January");
break;
case (2):
printf("The month is February");
break;
case (3):
printf("The month is March");
break;
case (4):
printf("The month is April");
break;
case (5):
printf("The month is May");
break;
case (6):
printf("The month is June");
break;
case (7):
printf("The month is July");
break;
case (8):
printf("The month is August");
break;
case (9):
printf("The month is September");
break;
case (10):
printf("The month is October");
break;
case (11):
printf("The month is November");
break;
case (12):
printf("The month is December");
break;
default:;
}
} else {
printf("not valid");
}
system("pause");
return 0;
}
谢谢你,对不起我的英语,但它不是我的母语。如果我没有清楚地解释自己,请告诉我。
【问题讨论】:
-
离题了,但是你最好还是看看数组来存储那些月份。你的代码会小很多...
-
为什么
return没有括号,比如return (0),case有括号? -
归根结底,双方都完成了工作。在我看来,第一个更干净,性能会稍微好一些,因为它需要的比较少。性能不会显着提高,打印比比较花费的时间要长得多,因此差异不应该是明显的。
-
@UlrichEckhardt:这些是括号,
return或case不需要。 OP 解释了为什么他认为它们很有用,但几乎没有人会这样做。
标签: c if-statement optimization switch-statement