我想将矩阵(3x3数组)发送到另一个函数,以便将它乘以某些东西。 但我希望这个矩阵的内容是有条件的。
APPROCH#1:
typedef float Mat3[3][3];
void rotate(Point *p, float theta){
int choice = ((int)theta/90)%4;
switch(choice){
case 0: matMult(p, {{1.0,0.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0}}); break;
case 1: matMult(p, {{0.0,-1.0,0.0}, {1.0,0.0,0.0}, {0.0,0.0,1.0}}); break;
case 2: matMult(p, {{-1.0,0.0,0.0}, {0.0,-1.0,0.0}, {0.0,0.0,1.0}}); break;
case 3: matMult(p, {{0.0,1.0,0.0}, {-1.0,0.0,0.0}, {0.0,0.0,1.0}}); break;
default: matMult(p, {{1.0,0.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0}}); break;
}
}
APPROACH#2:
void rotate(Point *p, float theta){
int choice = ((int)theta/90)%4;
Mat3 matrix = NIL;
switch(choice){
case 0: matrix = {{1.0,0.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0}}; break;
case 1: matrix = {{0.0,-1.0,0.0}, {1.0,0.0,0.0}, {0.0,0.0,1.0}}; break;
case 2: matrix = {{-1.0,0.0,0.0}, {0.0,-1.0,0.0}, {0.0,0.0,1.0}}; break;
case 3: matrix = {{0.0,1.0,0.0}, {-1.0,0.0,0.0}, {0.0,0.0,1.0}}; break;
default: matrix = {{1.0,0.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0}}; break;
}
matMult(p, matrix);
}
APPROACH#3
void rotate(Point *p, float theta){
int choice = ((int)theta/90)%4;
switch(choice){
case 0: Mat3 matrix = {{1.0,0.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0}}; break;
case 1: Mat3 matrix = {{0.0,-1.0,0.0}, {1.0,0.0,0.0}, {0.0,0.0,1.0}}; break;
case 2: Mat3 matrix = {{-1.0,0.0,0.0}, {0.0,-1.0,0.0}, {0.0,0.0,1.0}}; break;
case 3: Mat3 matrix = {{0.0,1.0,0.0}, {-1.0,0.0,0.0}, {0.0,0.0,1.0}}; break;
default: Mat3 matrix = {{1.0,0.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0}}; break;
}
matMult(p, matrix);
}
他们都没有,工作和我得到大约50个关于}或}的错误;在错误的地方,我很确定不是问题。有任何想法吗?感谢
答案 0 :(得分:1)
无法在C中分配矩阵,只能初始化矩阵或分配其各个组件。
有几种方法可以在这里进行,最简单的方法
也许不是switch
而是Mat3
static Mat3 const matrix[] = {
{{1.0,0.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0}},
{{0.0,-1.0,0.0}, {1.0,0.0,0.0}, {0.0,0.0,1.0}},
{{-1.0,0.0,0.0}, {0.0,-1.0,0.0}, {0.0,0.0,1.0}},
{{0.0,1.0,0.0}, {-1.0,0.0,0.0}, {0.0,0.0,1.0}},
};
unsigned choice = ((unsigned)(theta/90))%4u;
matMult(p, matrix[choice]);
const
,因为它看起来是你的第二个参数
功能是只读的。static
只在真实之前分配并初始化了一次
执行代码。unsigned
值,choice
保证%
的算术确实会产生从0
到3
的值,而不会产生负值。答案 1 :(得分:0)
复合文字可以在C99之后使用。 你可以写如下:,
void rotate(Point *p, float theta){
int choice = ((int)theta/90)%4;
switch(choice){
case 0: matMult(p, (Mat3){{1.0,0.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0}}); break;
case 1: matMult(p, (Mat3){{0.0,-1.0,0.0}, {1.0,0.0,0.0}, {0.0,0.0,1.0}}); break;
case 2: matMult(p, (Mat3){{-1.0,0.0,0.0}, {0.0,-1.0,0.0}, {0.0,0.0,1.0}}); break;
case 3: matMult(p, (Mat3){{0.0,1.0,0.0}, {-1.0,0.0,0.0}, {0.0,0.0,1.0}}); break;
default: matMult(p, (Mat3){{1.0,0.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0}}); break;
}
}