C switch 语句中的大于和小于 [英] Larger than and less than in C switch statement
问题描述
我正在尝试编写一个有很多比较的代码
I'm trying to write a code that has a lot of comparison
在QUANT.C"中编写一个量化"数字的程序.读取一个整数x"并测试它,产生以下输出:
Write a program in "QUANT.C" which "quantifies" numbers. Read an integer "x" and test it, producing the following output:
x 大于或等于 1000 打印非常积极"
x 从 999 到 100(包括 100)打印非常积极"
x 在 100 和 0 之间打印正"
x 正好 0 打印零"
x 在 0 到 -100 之间打印负"
x 从 -100 到 -999(包括 -100)打印非常负面"
x 小于或等于 -1000 打印非常负面"
x greater than or equal to 1000 print "hugely positive"
x from 999 to 100 (including 100) print "very positive"
x between 100 and 0 print "positive"
x exactly 0 print "zero"
x between 0 and -100 print "negative"
x from -100 to -999 (including -100) print "very negative"
x less than or equal to -1000 print "hugely negative"
因此 -10 将打印负面"、-100非常负面"和 458非常正面".
Thus -10 would print "negative", -100 "very negative" and 458 "very positive".
然后我尝试使用 switch 语句来解决它,但是没有用.我必须使用 if
语句来解决它还是有一种方法可以使用 switch 语句来解决它?
Then I tried to solve it using a switch statement, but it didn't work. Do I have to solve it using an if
statement or there is a method to solve it using a switch statement?
#include <stdio.h>
int main(void)
{
int a=0;
printf("please enter a number :
");
scanf("%i",&a);
switch(a)
{
case (a>1000):
printf("hugely positive");
break;
case (a>=100 && a<999):
printf("very positive");
break;
case (a>=0 && a<100):
printf("positive");
break;
case 0:
printf("zero");
break;
case (a>-100 && a<0):
printf("negative");
break;
case (a<-100 && a>-999):
printf("very negative");
break;
case (a<=-1000):
printf("hugely negative");
break;
return 0;
}
推荐答案
没有干净的方法可以用 switch 解决这个问题,因为 case 需要是整数类型.看看 if-else if-else.
There is no clean way to solve this with switch, as cases need to be integral types. Have a look at if-else if-else.
这篇关于C switch 语句中的大于和小于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!