![]() ![]() |
|
计算机二级辅导:C语言条件控制语句(三) | |
作者:佚名 文章来源:不详 点击数 更新时间:2008/4/18 13:58:02 文章录入:杜斌 责任编辑:杜斌 | |
|
|
程序如下: #include 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Ýays\n",month,day); }
[例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 #include 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:únd%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! |
|
![]() ![]() |