大于和小于switch语句C

我正在尝试编写一个有很多比较的代码

在“QUANT.C”中编写一个“量化”数字的程序。 读取整数“x”并测试它,产生以下输出:x大于或等于1000打印“巨大正面”x从999到100(包括100)打印“非常正”x在100和0之间打印“正面” x正好0打印“零”x介于0和-100之间打印“负”x从-100到-999(包括-100)打印“非常负”x小于或等于-1000打印“非常消极”因此-10将打印“负面”,-100“非常消极”和458“非常积极”。 

然后我尝试使用开关解决它,但它不起作用,我是否必须使用if语句解决它或有一个方法来解决它使用开关?


#include int main(void) { int a=0; printf("please enter a number : \n"); scanf("%i",&a); switch(a) { case (a>1000): printf("hugely positive"); break; case (a>=100 && a=0 && a-100 && a<0): printf("negative"); break; case (a-999): printf("very negative"); break; case (a<=-1000): printf("hugely negative"); break; return 0; }

没有干净的方法来解决这个问题,因为案例需要是整体类型。 看看if-else if-else。

无开关 if-else-less方法:

 #include  int main(void) { int a=0, i; struct { int value; const char *description; } list[] = { { -999, "hugely negative" }, { -99, "very negative" }, { 0, "negative" }, { 1, "zero" }, { 100, "positive" }, { 1000, "very positive" }, { 1001, "hugely positive" } }; printf("please enter a number : \n"); scanf("%i",&a); for (i=0; i<6 && a>=list[i].value; i++) ; printf ("%s\n", list[i].description); return 0; } 

for循环不包含代码(只有一个空语句; )但是当输入的值a等于或大于数组中的value元素时,它仍然在数组上运行并返回值。 此时, i保存要打印的description的索引值。

如果您正在使用gcc,那么您将获得“运气”,因为它通过使用语言扩展支持您想要的内容:

 #include  ... switch(a) { case 1000 ... INT_MAX: // note: cannot omit the space between 1000 and ... printf("hugely positive"); break; case 100 ... 999: printf("very positive"); break; ... } 

这是非标准的,其他编译器将无法理解您的代码。 通常会提到您应该仅使用标准function(“可移植性”)编写程序。

所以考虑使用“简化的” if-elseif-else结构:

 if (a >= 1000) { printf("hugely positive"); } else if (a >= 100) { printf("very positive"); } else if ... ... else // might put a helpful comment here, like "a <= -1000" { printf("hugely negative"); } 

(a>1000)评估为1 [true]或0 [false]。

编译并将得到错误

 test_15.c:12: error: case label does not reduce to an integer constant 

这意味着,您必须为case标签使用integer constant量值。 If-else if-else循环应该适用于这种情况。

这可能有点太晚了但是:

 switch( option(a) ){ case (0): ... case (1): ... case (2): ... case (n): ... 

其中option()函数只是if else的函数。 它可以让您保持开关的清晰外观,逻辑部件在其他地方。

为什么你喜欢使用开关?

我问,因为这听起来像是一个“家庭作业问题”。 编译器应该像切换一样有效地处理if / else构造(即使你没有处理范围)。

Switch无法像您所示的那样处理范围,但是您可以通过首先对输入进行分类(使用if / else)然后使用switch语句输出答案来找到包含切换的方法。