gpt4 book ai didi

c - 大于和小于 C switch 语句

转载 作者:太空狗 更新时间:2023-10-29 16:33:50 24 4
gpt4 key购买 nike

我正在尝试编写具有大量比较的代码

Write a program in “QUANT.C” which “quantifies” numbers. Read an integer “x” and test it, producing the following output:

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”

Thus -10 would print “negative”, -100 “very negative” and 458 “very positive”.

然后我尝试用switch语句来解决,但是没有用。我是否必须使用 if 语句来解决它,或者有一种方法可以使用 switch 语句来解决它?

#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;
}

最佳答案

没有干净的方法可以用 switch 解决这个问题,因为 case 需要是整数类型。看看 if-else if-else。

关于c - 大于和小于 C switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20972297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com