3333.txt

来自「用java写的线性方程组求解」· 文本 代码 · 共 96 行

TXT
96
字号
 import java.io.*; 
public class linearEquations 
{ 
public static void main(String [] args) throws IOException 
{ 
String s1; 
int i,j,rows,cols; 
double augmented[][]; 
boolean solution; 

InputStreamReader isr=new InputStreamReader(System.in); 
BufferedReader br=new BufferedReader(isr); 
System.out.print("Enter the number of linear equations:"); 
s1=br.readLine(); 
rows=Integer.parseInt(s1); 
cols=rows+1; 
augmented=new double[rows][cols]; 
for (i=0;i<rows;i++) 
for (j=0;j<(cols-1);j++) 
{ 
System.out.print("Enter the coefficients for equation "+(i+1)+"variable "+(j+1)+":"); 
s1=br.readLine(); 
augmented[i][j]=Double.parseDouble(s1); 
} 
for (i=0;i<rows;i++) 
{ 
System.out.print("Enter the known coefficients for equation "+(i+1)+":"); 
s1=br.readLine(); 
augmented[i][cols-1]=Double.parseDouble(s1); 
} 

solution=gaussian(augmented); 
if (solution) 
display(augmented); 
else 
System.out.println("\nA unique solution does not exist for these equations."); 

} 

public static boolean gaussian(double matrix[][]) 
{ 
int i,j,k,row,numeqs; 
double pivot,factor,temp; 
boolean solution; 
numeqs=matrix.length; 
for (i=0;i<numeqs;i++) 
{ 
pivot=matrix[i][i]; 
row=i+1; 
if (pivot==0.0) 
{ 
while (pivot==0.0 && row<numeqs) 
{ 
if (matrix[row][i]!=0.0) 
pivot=matrix[row][i]; 
else 
row++; 
} 
if (pivot==0.0) 
return false; 
else 
for (j=1;j<=numeqs;j++) 
{ 
temp=matrix[i][j]; 
matrix[i][j]=matrix[row][j]; 
matrix[row][j]=temp; 
} 
} 

pivot=matrix[i][i]; 
for (j=0;j<=numeqs;j++) 
matrix[i][j]=matrix[i][j]/pivot; 
for(k=0;k<numeqs;k++) 
{ 
factor=-matrix[k][i]; 
if (k!=i) 
{ 
for (j=0;j<=numeqs;j++) 
matrix[k][j]+=factor*matrix[i][j]; 
} 
} 


} 
return true; 
} 

public static void display(double matrix[][]) 
{ 
int i; 
System.out.println("\nThe solution is: "); 
for (i=0;i<matrix.length;i++) 
System.out.println("X"+(i+1)+"="+matrix[i][matrix.length]); 
} 
}  
 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?