我正在研究老师给我们的练习题,它可以计算二次方程的根。据说我们不使用if,而是使用switch_case。在此代码中,我要求用户输入三个整数值,经过一些数学运算后,结果是需要定义的增量,如果该增量为正,负或等于0,然后对其进行适当的运算。如下所示:
int opt=0,a,b,c,delta;
double x1,x2,real,img;
printf("Enter the integer coefficients a, b and c respectively: ");
scanf("%i%i%i",&a,&b,&c);
delta = b*b - 4*a*c;
现在将正确的操作链接到增量符号,我需要像这样使用switch_case:
switch(delta){
case delta>0:
x1=(-b+sqrt(delta))/(2*a);
x2=(-b-sqrt(delta))/(2*a);
printf("the roots of the quadratic equation you entered are x1=%.3lf & x2=%.3lf",x1,x2);
break;
case 0:
x1=(-b)/(2*a);
printf("the roots of the quadratic equation you entered are the same and equal to x=%.3lf",x1);
break;
case delta<0:
real=(-b)/(2*a);
img=sqrt(-delta)/(2*a);
printf("the roots of the quadratic equation you entered is x1=%.3lf+i%.3lf & x2=%.3lf-i%.3lf",real,img,real,img);
break;
default:
printf("an error accured during operation");
}
但是由于增量不是预先定义的,而是在代码执行期间计算的,所以大小写不起作用,并且我遇到错误“大小写标签未减少为整数常量”是否有任何技巧或常规方法将switch_case与此类变量一起使用(未预定义)?
[switch
语句仅允许使用整数常量,因此您的解决方案无法使用。
但是考虑到逻辑运算将给出一个分别为true和false的值为1或0的整数,您可以尝试:
switch (delta > 0)
{
case 1:
x1 = (-b + sqrt(delta)) / (2 * a);
x2 = (-b - sqrt(delta)) / (2 * a);
printf("the roots of the quadratic equation you entered are x1=%.3lf & x2=%.3lf", x1, x2);
break;
case 0:
switch (delta == 0)
{
case 1:
x1 = (-b) / (2 * a);
printf("the roots of the quadratic equation you entered are the same and equal to x=%.3lf", x1);
break;
case 0: //delta < 0
real = (-b) / (2 * a);
img = sqrt(-delta) / (2 * a);
printf("the roots of the quadratic equation you entered is x1=%.3lf+i%.3lf & x2=%.3lf-i%.3lf", real, img, real, img);
break;
}
}
尝试以下操作:
int sign = (0 < delta) - (0 > delta);
switch(sign)
{
case -1: /* 0 > delta */
...
break;
case 0: /* 0 = delta */
...
break;
case 1: /* 0 < delta */
...
break;
default:
/* Should never arrive here. */
}