我尝试定义一个函数来计算两个原子之间的距离。我在主函数中定义了一个二维数组来存储 m 个原子的坐标,例如nn[m][3],m是原子索引,3代表x<-1,y<-2,z<-3。
但是当我定义函数--> float dist() { } 时,我的 Dev C++ 编译器说 'nn' 未声明(首先使用此函数)(每个未声明的标识符对于它出现的每个函数仅报告一次。)
以下是我定义函数dist()的代码,错误发生在x1=nn[a][0]行 谢谢你,最好的
float dist(int a, int b){ // a,b are parameters of function dist(), a is one order of
//a atom, b is another, e.g. nn[a][x,y,z], and nn[b][x,y,z]
float d;
float f1(float);// f1 is a fn to calculate the square of a number
float x1,x2,y1,y2,z1,z3;
x1=nn[a][0];
x2=nn[b][0];
y1=nn[a][1];
y2=nn[b][1];
z1=nn[a][2];
z2=nn[b][2];
float nn[a][0],nn[a][1],nn[a][2],nn[b][0],nn[b][1],nn[b][2];
d=sqrt(f1(x1-x2)+f1(y1-y2)+f1(z1-z2));
return d;
}
这就是我现在拥有的:
// build an array for 4 Molecules, with initial radius between 2 nearest molecules
// number of 2 nearest number is n-1
// number of not nearest neighbor
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float f1(float p){ //calculat the square
float k;
k=p*p;
return k;
}
float dist(int a, int b){ // a,b are parameters of function dist(), a is one order of
//a atom, b is another, e.g. nn[a][x,y,z], and nn[b][x,y,z]
float d;
float f1(float);// f1 is a fn to calculate the square of a number
float x1,x2,y1,y2,z1,z3;
x1=nn[a][0];
x2=nn[b][0];
y1=nn[a][1];
y2=nn[b][1];
z1=nn[a][2];
z2=nn[b][2];
float nn[a][0],nn[a][1],nn[a][2],nn[b][0],nn[b][1],nn[b][2];
d=sqrt(f1(x1-x2)+f1(y1-y2)+f1(z1-z2));
return d;
}
int main (void)
{
int n=4;// # of molecules
int i=0,j=0,k=0;rj,rk;//i,j,k are dummy variables, rj, rk are the the size of array rn[],rd[]
rj=(n-1)-1;//the # of nearest neighbor of 4 molecules, rj=(n-1)-1,-1 for c starts at 0
rk=n*(n-1)/2-(n-1)-1;//the # of non-nearest neighbor of 4 molecules, for n molecules, it will be
float rn[rj],rd[rk];// nn is the number array of the atoms
// nn[][] is the coordinates of the atom, n[][0]<-x,n[][1]<-y,n[][2]<-z,
// rn[] is the distance between nearest neighbor
// rk[] is the distance between non-nearest neighbors
/* give intiate coordinate */
int nn[4][3]={{0,0,0},{1,0,0},{2,0,0},{3,0,0}};
for(j=0;j<n;j++)
{
{printf("\n");
for(i=0;i<3;i++)
printf("nn[%d][%d] is %d ",j,i,nn[j][i]);
}
printf("\n");
}
printf("\n");
float d,dd;
printf("%d, \n%d \n",nn[1][0],nn[2][0]);
d=sqrt(f1(nn[1][0]-nn[2][0])+f1(nn[1][1]-nn[2][1])+f1(nn[1][2]-nn[2][2])); //calculate the distance
dd=dist(1,2); // test the function
printf("%f\n%f\n",d,dd);
system("pause");
return 0;
}
最佳答案
改变
float dist(int a, int b){
到
float dist(int a, int b, int nn[4][3]){
改变
dd=dist(1,2);
至
dd=dist(1,2, nn);
改变
int i=0,j=0,k=0;rj,rk;
至
int i=0,j=0,k=0,rj,rk;
改变
float nn[a][0],nn[a][1],nn[a][2],nn[b][0],nn[b][1],nn[b][2];
至
//float nn[a][0],nn[a][1],nn[a][2],nn[b][0],nn[b][1],nn[b][2];
改变
float x1,x2,y1,y2,z1,z3;
至
float x1,x2,y1,y2,z1,z2;
关于c - 如何将数组包含到 C 函数定义中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25042543/