我正在尝试在OpenGL中制作游戏并想要移动相机。我使用这段代码完成了它:
t.calculations(&t1, 5.54, 1.54, 10, 10, 1);
t.calculations(&t2, 5.54, 1.54, 10, 10, 1);
t.calculations(&t3, 5.54, 1.54, 10, 10, 1);
t.calculations(&t4, 5.54, 1.54, 10, 10, 1);
t.calculations(&t5, 5.54, 1.54, 10, 10, 1);
t.calculations(&t6, 5.54, 1.54, 10, 10, 1);
t.calculations(&t7, 5.54, 1.54, 10, 10, 1);
t.calculations(&t8, 5.54, 1.54, 10, 10, 1);
t.calculations(&t9, 5.54, 1.54, 10, 10, 1);
t.calculations(&t10, 5.54, 1.54, 10, 10 ,1);
t.calculations(&t11, 5.54, 1.54, 10, 10, 1);
t.calculations(&t12, 5.54, 1.54, 10, 10, 1);
t.calculations(&t13, 5.54, 1.54, 10, 10, 1);
t.calculations(&t14, 5.54, 1.54, 10, 10, 1);
t.calculations(&t15, 5.54, 1.54, 10, 10, 1);
t.calculations(&t16, 5.54, 1.54, 10, 10, 1);
t.calculations(&t17, 5.54, 1.54, 10, 10, 1);
t.calculations(&t18, 5.54, 1.54, 10, 10, 1);
但是你可以看到这看起来像是过多的代码重复。我曾尝试使用以下方法而不是上述方法:
for (int i = 1; i < 19; i++) {
t.calculations(&t+i, 5.54, 1.54, 10, 10, 1);
}
但它不起作用。谁能告诉我一个替代解决方案?
答案 0 :(得分:2)
假设t i 变量都是相同的类型且类型是double:
// The following sentence declares an array initialized with the 18 t variables
// think of this array as a slot container of values, the following is just syntax
// to declare and initialize the array
// IMPORTANT: Once the array is initialized, you can't modify its structure, you can
// replace the content of every cell, but, you can add neither remove elements from it
double t[] = { t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18 };
// Then, you can read every cell of the array using the [] operator like this:
// (Another important hint, arrays starts from '0')
for (int 0 = 1; i < 18; i++) {
// You take the address of every ti variable stored in each "cell" of the array
t.calculations(&t[i], 5.54, 1.54, 10, 10, 1);
}
或者,使用较不详细的语法(但相当复杂),上面的代码可以表示为:
for (int i = 0; i < 18; i++) {
t.calculations(t + i, 5.54, 1.54, 10, 10, 1);
}
有关详细信息,请查看c / c ++中的在线documentation和数组教程。类似的语法广泛用于其他语言