#include<iostream>
#include<cstdio>
#include<iomanip>
#include<vector>
#include<cmath>
using namespace std;
const int maxn = 10;
const int inf = 0x3f3f3f3f;
double a[maxn][maxn];
struct st{
int x,y;
};
vector<st>first; // 存首非0元的坐标
int n,m;//n为行 m 为列
int count = 0;
void puutDouble(double jian){ // 化为分数
if((int)jian == jian) {
printf("%0.1lf",jian);
return ;
}
int j;
double xx;
for( j = 1;j <= 99;j++){
xx = jian*j;
if(xx > 0) xx += 0.005;
else xx -= 0.005;
if(abs( (int) xx - xx ) <= 0.01 ){
break;
}
}
cout<<(int)xx<<"/"<<j;
}
void putt(){ //输出
for(int i = 1;i <= n;i++){
for(int j = 1;j <=m ;j++){
if(abs(a[i][j]) < 0.001) a[i][j] = 0;
if((int)a[i][j]!=a[i][j]){
cout<<setw(2)<<"(";
puutDouble(a[i][j]);
cout<<")";
}
else
cout<<setw(6)<<a[i][j];
// printf("%-.1lf ",a[i][j]);
}
printf("\n");
}
}
void divi(int y,int x){//化为阶梯
if(y>n||x>m) return;
bool f = 0;
if(abs(a[y][x]) < 1 &&a[y][x]!=0){ //判断是否要自乘,目前小于1才自乘(大于一自乘还存在问题)
double xx = 1 / a[y][x];
if(xx == 0||abs(xx)<=inf) {
// cout<<"r"<<d<<"*"<<x<<endl;
for(int i = x;i <= m;i++){
a[y][i] *= xx;
}
puutDouble(xx);
cout<<"*r"<<y<<endl;
cout<<"第"<<++count<<"次变换"<<endl;
putt();
cout<<"------divi自乘线----------"<<endl;
}}
int i = y+1;
for(int i = y+1;i <= n;i++){
double jian = -a[i][x]*1.0 / a[y][x]*1.0 ;
if(jian == 0||abs(jian)>=inf) continue;
cout<<"r"<<i<<"+(";
puutDouble(jian);
cout<<")*"<<"r"<<y<<endl;
f = 1;
for(int j = x;j <= m;j++){
a[i][j] = a[i][j] + a[y][j]*jian;
}
}
if(f){
cout<<"第"<<++count<<"次变换"<<endl;
putt();
cout<<"---------divi1-----------"<<endl;
}
}
void divi2(){//化为最简
int cont = 0;
for(int z = 0;z < first.size();z++){
bool f = 0;
int y = first[z].y;
int x = first[z].x;
if(a[y][x] == 0||y == 1) continue;
for(int i = y-1;i >= 1;i-- ){
double jian = -a[i][x]*1.0 / a[y][x]*1.0 ;
if(jian == 0||jian>=inf) continue;
cout<<"r"<<i<<"+(";
puutDouble(jian);
cout<<")*"<<"r"<<y<<endl;
f = 1;
for(int j = x;j <= m;j++){
a[i][j] = a[i][j] + a[y][j]*jian;
}
}
if(f){
cout<<"第"<<++cont<<"次变换"<<endl;
putt();
cout<<"-------divi2-----------"<<endl;
}
}
}
int main()
{
cout<<"输入矩阵的行数和列数:"<<endl;
cin>>n>>m;
cout<<"输入该矩阵"<<endl;
for(int i = 1;i <= n;i++){
for(int j = 1;j <= m;j++){
cin>>a[i][j];
}
}
cout<<"------------------------"<<endl;
for(int i = 1,j = 1;i <= n&&j <= m;i++,j++){
while(a[i][j] == 0) {// 如果下一个对角线为0 则往右移动
j++;
if(j>m&&i<n){//如果这一行都为0 那么把下一行交换上来,现在这一行放在最下面,重新检查这一行
j = i;
for(int z = 1;z <= m ;z++){
swap(a[i][z],a[n][z]);
}
for(int c = i;c < n - 1;c++)
for(int z = 1;z <=m;z++){
swap(a[c][z],a[c+1][z]);
}
cout<<"第"<<++count<<"次变换"<<endl;
cout<<"r"<<i<<"与"<<"r"<<i+1<<"交换"<<endl;
putt();
}
}
divi(i,j);
st a;
a.y = i;a.x = j;
first.push_back(a);
}
cout<<"已转换为行阶梯型矩阵"<<endl;
cout<<"--------------------"<<endl;
divi2();
cout<<"已转换为行最简矩阵"<<endl;
system("pause");
return 0;
}
矩阵化为行阶梯型矩阵 和 化为行最简矩阵 【显示出每一步的步骤,有源码】
需积分: 1 69 浏览量
2020-05-28
17:11:16
上传
评论 3
收藏 376KB RAR 举报
ysyyhhh
- 粉丝: 19
- 资源: 1