求个矩阵乘法的源码(C++的)
自己写不出来了,从文件读取数据的时候赋值搞不清楚……
要求:从两个TXT文件中各读取一个超级大的矩阵,将读取出的两矩阵相乘,将所得的第三个矩阵写到第三个TXT文件中,读取的矩阵和输出的矩阵中,每行的两个相邻数用逗号隔开,计算运算时间,并将时间写入第三个文件中。
另附已经写好的JAVA源码如下:
import java.util.*;
import java.io.*;
public class Matrix {
public static void main(String[] args) {
Date date = new Date();
long previousTime = date.getTime();
long lastTime = 0;
//设置1个参数,如果等于1,则计算并把结果写入文件,且计算时间,如果等于2,计算并计算时间,不写文件,但计算结果,在 屏幕输出 如果等于3,only计算,不在屏幕输出结果,只显示计算时间~
int choose = 0;
try {
choose = Integer.parseInt(args[0]);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Please input a number to choose the way that you want to display!");
System.exit(-1);
} catch(Exception e) {
System.out.println("Please input a correct number!");
System.exit(-1);
}
//将结果输出到文件中
File f = new File("f://1.txt");
String strEncode = "UTF-8";
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), strEncode));
} catch(IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
int Cut = 0;
int[][] b = ReadFile.read("F://3.txt");
int[][] c = ReadFile.read("F://4.txt");
int[][] a = null;
for(int i=0; i<b.length; i++) {
for(int j=0; j<b[i].length; j++) {
a = new int[b.length][b[i].length];
a[i][j] = b[i][j] * c[i][j];
Cut += 1;
sb.append(a[i][j] + " ");
}
sb.append("\r\n");
}
date = new Date();
lastTime = date.getTime();
long useTime = lastTime - previousTime;
if(choose == 1) {
try {
bw.write(sb.toString());
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
bw.close();
} catch(IOException e) {
e.printStackTrace();
}
}
System.out.println("运行结果输出到F://1.txt文件中");
}
if(choose == 2) {
System.out.println("-共进行计算" + Cut + "次!");
System.out.println(sb.toString());
}
if(choose == 3) {
System.out.println("一共运行" + useTime + "毫秒");
}
}
}
class ReadFile {
public static int[][] read(String filename) {
int x = 0;
int y = 0;
Map m = new HashMap();
File f = new File(filename);
BufferedReader br = null;
String str = new String();
String[] s = null;
try {
br = new BufferedReader(new FileReader(f));
} catch(FileNotFoundException e) {
System.out.println("File not found!");
System.exit(-1);
}
try {
while((str = br.readLine()) != null) {
s = trim(str).split(",");
y = s.length;
x += 1;
m.put(x, s);
}
} catch(IOException e) {
e.printStackTrace();
}
int[][] array = new int[x][y];
for(int i=0; i<x; i++) {
for(int j=0; j<y; j++) {
String[] strs = (String[])m.get(i+1);
array[i][j] = Integer.parseInt(strs[j]);
}
}
return array;
}
public static String trim(String str) {
str = str.replaceAll(" ", "");
return str;
}
}