当整型变量i的值为1、2或3时,执行语句1,当i的值为4或5时,执行语句2,否则,执行 语句3。 [例3-9]输入月份,打印1999年该月有几天。 程序如下: #include<stdio.h> main() { int month; int day; printf("please input the month number:"); scanf("%d",&month); switch(month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12:day=31; break; case 4: case 6: case 9: case 11:day=30; break; case 2:day=28; break; default:day=-1; } if day=-1 printf("Invalid month input !/n"); else printf("1999.%dhas%ddays/n",month,day); } 3.3.3程序应用举例 [例3-10]解一元二次方程ax2+bx+c=0,a、b、c由键盘输入。 分析:对系数a、b、c考虑以下情形 1)若a=0: ①b<>0,则x=-c/b; ②b=0,则:①c=0,则x无定根; ②c<>0,则x无解。 2)若a<>0; ①b2-4ac>0,有两个不等的实根; ②b2-4ac=0,有两个相等的实根; ③b2-4ac<0,有两个共轭复根。 用嵌套的if语句完成。程序如下: #include<math.h> #include<stdio.h> main() { float a,b,c,s,x1,x2; doublet; printf("please input a,b,c:"); scanf("%f%f%f",&a,&b,&c); if(a==0.0) if(b!=0.0) printf("the root is:%f/n",-c/b); elseif(c==0.0) printf("x is inexactive/n"); else printf("no root !/n"); else { s=b*b-4*a*c; if(s>=0.0) if(s>0.0) { t=sqrt(s); x1=-0.5*(b+t)/a; x2=-0.5*(b-t)/a; printf("There are two different roots:%fand%f,/xn1",x2); } else printf("There are two equal roots:%f/n",-0.5*b/a); else { t=sqrt(-s); x1=-0.5*b/a;/*实部*/ x2=abs(0.5*t/a);/*虚部的绝对值*/ printf("There are two virtual roots:"); printf("%f+i%f/t/t%f-i%f/n",x1,x2,x1,x2); } } } 运行结果如下: RUN please input a,b,c:123 There are two virtual roots: -1.000000+i1.000000-1.000000-i1.000000 RNU pleaseinputa,b,c:253 There are two different roots:-1.500000and-1.000000 RNU please input a,b,c:003¿ No root!