【发布时间】:2016-01-26 04:40:09
【问题描述】:
我还是 C++ 的新手,我一直在尝试将一些给我的意大利面条代码模块化。到目前为止(除了学习如何使用 git 和安装 rarray 库以用它们替换自动数组)我对如何模块化事物然后通过 make 编译它感到有点困惑。
我知道我必须在头文件中创建原型,从我的函数创建我的目标文件,然后使用“驱动程序”代码编译它们。运行/编写 make 文件不是我关心的问题,而是如何开始像这样模块化代码;我不知道如何制作修改数组的函数!
任何指向正确方向的指针都会令人惊叹。如有必要,我可以澄清更多。
#include <cmath>
#include <iostream>
#include <rarray> // Including the rarray library.
#include <rarrayio> // rarray input/output, if necessary. Probably not.
int main()
{
// ants walk on a table
rarray<float,2> number_of_ants(356,356);
rarray<float,2> new_number_of_ants(356,356);
rarray<float,2> velocity_of_ants(356,356);
const int total_ants = 1010; // initial number of ants
// initialize
for (int i=0;i<356;i++) {
for (int j=0;j<356;j++) {
velocity_of_ants[i][j] = M_PI*(sin((2*M_PI*(i+j))/3560)+1);
}
}
int n = 0;
float z = 0;
for (int i=0;i<356;i++) {
for (int j=0;j<356;j++) {
number_of_ants[i][j] = 0.0;
}
}
while (n < total_ants) {
for (int i=0;i<356;i++) {
for (int j=0;j<356;j++) {
z += sin(0.3*(i+j));
if (z>1 and n!=total_ants) {
number_of_ants[i][j] += 1;
n += 1;
}
}
}
}
// run simulation
for (int t = 0; t < 40; t++) {
float totants = 0.0;
for (int i=0;i<356;i++) {
for (int j=0;j<356;j++) {
totants += number_of_ants[i][j];
}
}
std::cout << t<< " " << totants << std::endl;
for (int i=0;i<356;i++) {
for (int j=0;j<356;j++) {
new_number_of_ants[i][j] = 0.0;
}
}
for (int i=0;i<356;i++) {
for (int j=0;j<356;j++) {
int di = 1.9*sin(velocity_of_ants[i][j]);
int dj = 1.9*cos(velocity_of_ants[i][j]);
int i2 = i + di;
int j2 = j + dj;
// some ants do not walk
new_number_of_ants[i][j]+=0.8*number_of_ants[i][j];
// the rest of the ants walk, but some fall of the table
if (i2>0 and i2>=356 and j2<0 and j2>=356) {
new_number_of_ants[i2][j2]+=0.2*number_of_ants[i][j];
}
}
}
for (int i=0;i<356;i++) {
for (int j=0;j<356;j++) {
number_of_ants[i][j] = new_number_of_ants[i][j];
totants += number_of_ants[i][j];
}
}
}
return 0;
}
【问题讨论】:
-
您应该能够在函数参数中传递对数组对象的引用。但是,如果您使用的是 C 数组,则数组本身就是一个指针,因此将它传递给您的函数就足够了。
-
这将有助于首先用 cmets 识别每个代码块的用途,然后,您可以将这些块转换为函数并调用它们而不是原始代码。这一切都伴随着首先明确每个块存在的原因。
-
正如发布的答案所说,这不是意大利面条代码。它实际上非常干净且易于理解。试图在不了解数组的情况下“修复”它将是一个巨大的错误。在你对如何做出你认为(现在)必要的改变非常有信心之前,甚至不要碰它。
标签: c++ modular modularization