Orange1015 @ 2023-07-12 11:08:34
rt,90pts,各种调试无果。
#include<bits/stdc++.h>
using namespace std;
#define MAXN 105
#define EPS 1e-6
double a[MAXN][MAXN],ans[MAXN];
int n;
bool gauss(){
int r=0;
for(int i=1;i<=n;i++){
r=i;
for(int j=i+1;j<=n;j++){
if(fabs(a[j][i])>fabs(a[r][i])){
r=j;
}
}
if(fabs(a[r][i])<EPS) return 0;
if(i!=r){
for(int j=i;j<=n+1;j++){
swap(a[r][j],a[i][j]);
}
}
double del=a[i][i];
for(int j=i;j<=n+1;j++){
a[i][j]/=del;
}
for(int j=i+1;j<=n;j++){
del=a[j][i];
for(int k=i;k<=n+1;k++){
a[j][k]-=a[i][k]*del;
}
}
}
ans[n]=a[n][n+1];
for(int i=n-1;i>=1;i--){
ans[i]=a[i][n+1];
for(int j=i+1;j<=n;j++){
ans[i]-=(a[i][j]*ans[j]);
}
}
return 1;
}
int main(){
cin >> n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n+1;j++){
cin >> a[i][j];
}
}
if(gauss()){
for(int i=1;i<=n;i++){
printf("x%d=%.2lf\n",i,ans[i]);
}
}
else{
for (int i = 1; i <= n; i++)
{
bool f = true;
for (int j = 1; j <= n; j++) if (a[i][j] != 0)
{
f = false;
break;
}
if (f && a[i][n + 1] != 0)
{
puts("-1");
return 0;
}
}
puts("0");
}
return 0;
}
by AlexSong @ 2023-08-16 09:14:00
求关
#include<bits/stdc++.h>
using namespace std;
const int N = 55;
const double eps = 1e-8;
double a[N][N];
int n;
int gauss(){
int r,c;
for(c = 0,r = 0;c<n;c++){
int t = r;
for(int i = r;i<n;i++)
if(fabs(a[i][c])>fabs(a[t][c]))t = i;
if(fabs(a[t][c])<eps)continue;
for(int i = c;i<=n;i++)swap(a[r][i],a[t][i]);
for(int i = n;i>=c;i--)a[r][i]/=a[r][c];
for(int i = r+1;i<n;i++){
if(fabs(a[i][c])>eps){
for(int j = n;j>=c;j--){
a[i][j] -= a[i][c] * a[r][j];
}
}
}
r++;
}
if(r<n){
for(int i = r;i<n;i++){
if(fabs(a[i][n])>eps)return 2;
return 1;
}
}
for(int i = n-1;i>=0;i--)
for(int j = i+1;j<n;j++)a[i][n] -= a[i][j]*a[j][n];
return 0;
}
int main(){
scanf("%d",&n);
for(int i = 0;i<n;i++)
for(int j = 0;j<=n;j++)scanf("%lf",&a[i][j]);
int t = gauss();
if(t==2)return puts("-1"),0;
if(t==1)return puts("0"),0;
for(int i = 0;i<n;i++){
cout<<"x"<<i+1<<"=";
printf("%.2lf\n",a[i][n]);
}
return 0;
}