-(IBAction) balancer: (id) sender{
double M[4][4];
M[0][0] = 6.0;
M[0][1] = 0.0;
M[0][2] = -1.0;
M[0][3] = 0.0;
M[1][0] = 12.0;
M[1][1] = 0.0;
M[1][2] = 0.0;
M[1][3] = 2.0;
M[2][0] = 6.0;
M[2][1] = 2.0;
M[2][2] = -2.0;
M[2][3] = 1.0;
M[3][0] = 0.0;
M[3][1] = 0.0;
M[3][2] = 0.0;
M[3][3] = 0.0;
int rowCount = 4;
int columnCount = 4;
int lead = 0;
for (int r = 0; r < rowCount; r++) {
if (lead >= columnCount)
break;
int i = r;
while (M[i][lead] == 0) {
i++;
if (i == rowCount) {
i = r;
lead++;
if (lead == columnCount){
break;
}
}
}
double temp[4] ;
temp[0] = M[r][0];
temp[1] = M[r][1];
temp[2] = M[r][2];
temp[3] = M[r][3];
M[r][0] = M[i][0];
M[r][1] = M[i][1];
M[r][2] = M[i][2];
M[r][3] = M[i][3];
M[i][0] = temp[0];
M[i][1] = temp[1];
M[i][2] = temp[2];
M[i][3] = temp[3];
double lv = M[r][lead];
for (int j = 0; j < columnCount; j++)
M[r][j] = M[r][j] / lv;
for (int f = 0; f < rowCount; f++) {
if (f != r) {
double l = M[f][lead];
for (int j = 0; j < columnCount; j++)
M[f][j] = M[f][j] - l * M[r][j];
}
}
lead++;
}
NSString* myNewString = [NSString stringWithFormat:@"%g",M[0][3]];
label1.text = myNewString;
}
这是返回NaN,而它应该为M [0] [3]返回.16666667。对于如何解决这个问题,有任何的建议吗?
答案 0 :(得分:1)
您正在进行除法以获取M[r][j]
的值,您应该在执行除法之前检查lv ! = 0.0
。
double TOLERANCE = 1.0E-10;
if (fabs(lv) < TOLERANCE){
NSLog(@"Division over ZERO");
exit(1);
}
[edit]假设你的逻辑是正确的。