大于和小于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 : \n");
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;
}
推荐答案
没有干净的方法用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屋!