三、实验2:分支与循环程序设计
1. 实验目的
掌握分支与循环程序设计的方法和有关语句。
2. 实验内容
实验题2.1 计算一元二次方程ax²+bx+c=0
注意不同的根有不同的输出。
程序如下:
/*EX2-1*/
# include<stdio.h>
# include<math.h>
main( )
{
float a, b, c, d, x1, x2, re, im;
printf(“Input a, b, c:\n”);
scanf(“%f, %f, %f”, &a, &b, &c);
printf(“the equation”);
if(a= =0)
printf(“is not quadratie”);
else
d=b*b-4.0*a*c;
if(d= =0)
printf(“has two equal roots: %8.3fln”, -b/(2.0*a));
else
if(d>0)
{
x1=(-b+sqrt(d))/(2.0*a);
x2=(-b-sqrt(d))/(2.0*a);
printf(“has distinet real rools: %8.3f and %8.3f \n”, x1, x2);
}
else
{
re=-b/(2.0*a)
im=sqrt(-d)/(2.0*a);
printf(“has complex roots: \n”);
printf(“%8.3f+%8.3f \n”, re, im);
printf(“%8.3f-%8.3f \n”, re, im);
}
return 0;
參考答案:/*你后的编程要记住不要用全角的形式如"不要打成全角的”要不然是不会通过的,我帮你改过来了,*/
# include<stdio.h>
# include<math.h>
main( )
{
float a, b, c, d, x1, x2, re, im;
printf("Input a, b, c:\n");
scanf("%f,%f,%f", &a, &b, &c);
printf("the equation");
if(a==0)
printf("is not quadratie");
else
d=b*b-4.0*a*c;
if(d==0)
printf("has two equal roots: %8.3fln", -b/(2.0*a));
else
if(d>0)
{
x1=(-b+sqrt(d))/(2.0*a);
x2=(-b-sqrt(d))/(2.0*a);
printf("has distinet real rools: %8.3f and %8.3f \n", x1, x2);
}
else
{
re=-b/(2.0*a) ;
im=sqrt(-d)/(2.0*a);
printf("has complex roots: \n");
printf("%8.3f+%8.3f \n", re, im);
printf("%8.3f-%8.3f \n", re, im);
}
getch();
}