高中生程式解題系統:解方程

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。

題目連結 http://zerojudge.tw/ShowProblem?problemid=a410

Cramer's Rule來解,若有一聯立方程式如下(下圖取自Cramer's Rule):
\left\{{\begin{matrix}a_{1}x+b_{1}y&={\color {red}c_{1}}\\a_{2}x+b_{2}y&={\color {red}c_{2}}\end{matrix}}\right.

則x與y的解為(下圖取自Cramer's Rule):
{\displaystyle {\begin{aligned}x&={\frac {\begin{vmatrix}{\color {red}{c_{1}}}&b_{1}\\{\color {red}{c_{2}}}&b_{2}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}\\a_{2}&b_{2}\end{vmatrix}}}={{\color {red}c_{1}}b_{2}-b_{1}{\color {red}c_{2}} \over a_{1}b_{2}-b_{1}a_{2}},\quad y={\frac {\begin{vmatrix}a_{1}&{\color {red}{c_{1}}}\\a_{2}&{\color {red}{c_{2}}}\end{vmatrix}}{\begin{vmatrix}a_{1}&b_{1}\\a_{2}&b_{2}\end{vmatrix}}}={a_{1}{\color {red}c_{2}}-{\color {red}c_{1}}a_{2} \over a_{1}b_{2}-b_{1}a_{2}}\end{aligned}}.}


程式碼:
#include <cstdio>
using namespace std;
int main() {
 float a,b,c,d,e,f;
 
 while( scanf("%f%f%f%f%f%f",&a,&b,&c,&d,&e,&f) != EOF ){
  float det = a*e - b * d;
  float detX = c * e - b * f;
  float detY = a * f - c * d;
  if(det ==0 && detX ==0)
                printf("Too many\n");
        else if( det == 0)
                printf("No answer\n");
  else{
   printf("x=%.2f\n",detX / det);
   printf("y=%.2f\n",detY / det);
  }
 }
 return 0;
}

沒有留言:

張貼留言