首先,来编写一个函数solve,给定浮点数a,b,c,d,e,f,求解方程组ax+by=c,dx+ey=f。
任务1:使用assert宏,让解不唯一时异常退出。
#include<stdio.h>
#include<assert.h>
tpdedef double db;
void solve(db a,db b,db c,db d,db e,db f,db &x,db &y)
{
assert(a*e!=d*b);
x=(c*e-b*f)/(a*e-b*d);
y=(c*d-a*f)/(b*d-a*e);
}
int main()
{
db a,b,c,d,e,f,x,y;
scanf("%lf %lf %lf %lf %lf %lf",&a,&b,&c,&d,&e,&f);
ope(a,b,c,d,e,f,x,y);
printf("%lf %lf\n",x,y);
return 0;
}
/*
ax+by=c
dx+ey=f
当a/d≠b/e 时,该方程组有一组解。
当a/d=b/e=c/f 时,该方程组有无数组解。
当a/d=b/e≠c/f 时,该方程组无解。
*/
任务2:解不唯一时仍正常返回,但调用者有办法知道解的数量(无解、唯一解、无穷多解)。
#include<stdio.h>
#include<assert.h>
tpdedef double db;
int solve(db a,db b,db c,db d,db e,db f,db &x,db &y)
{
if(a*e==d*b)
{
if(a*f!=c*d)
return 0;
else
return -1;
}
if((a*e!=d*b)
return 1;
}
int main()
{
db a,b,c,d,e,f,x,y;
int flag;
scanf("%lf %lf %lf %lf %lf %lf",&a,&b,&c,&d,&e,&f);
flag=solve(a,b,c,d,e,f,x,y);
if(flag)
{
if(flag==-1)
printf("Countless answers.\n");
else
printf("No answer.\n");
}
else
printf("Only one answer.\n");
return 0;
}