将C代码转换为Java
有人能给我解释一下下面的两段代码是做什么的,以及Java中的等效代码是什么样子的吗
double* ptr;
ptr = (double*)malloc(10*_R_CONST*sizeof(double)+2048);
根据我对C语言的有限知识,我假设它正在声明一个指针ptr,设置指针的大小
这就是稍后在同一文件中调用的样子
ptr[10*n+2]=-RadtoMOA(atan(y/x));
ptr[10*n+0]=x/3;
ptr[10*n+1]=y*12;
ptr[10*n+2]=-RadtoMOA(atan(y/x));
ptr[10*n+3]=t+dt;
还有另一个类似的函数,我对C也不熟悉。带星号的两行是我特别想知道的
double GetRange(double* sln, int yardage){
**double size=sln[_R_CONST*10+1];**
if (yardage<size){
**return sln[10*yardage];**
}
else return 0;
}
对于这个问题的第一部分,这里是完整的代码,包括上面的摘录
double* ptr;
ptr = (double*)malloc(10*_R_CONST*sizeof(double)+2048);
double t=0;
double dt=0.5/Vi;
double v=0;
double vx=0, vx1=0, vy=0, vy1=0;
double dv=0, dvx=0, dvy=0;
double x=0, y=0;
double headwind=HeadWind(WindSpeed, WindAngle);
double crosswind=CrossWind(WindSpeed, WindAngle);
double Gy=GRAVITY*cos(DegtoRad((Angle + ZAngle)));
double Gx=GRAVITY*sin(DegtoRad((Angle + ZAngle)));
vx=Vi*cos(DegtoRad(ZAngle));
vy=Vi*sin(DegtoRad(ZAngle));
y=-SightHeight/12;
int n=0;
for (t=0;;t=t+dt){
vx1=vx, vy1=vy;
v=pow(pow(vx,2)+pow(vy,2),0.5);
dt=0.5/v;
// Compute acceleration using the drag function retardation
dv = retard(DragFunction,DragCoefficient,v+headwind);
dvx = -(vx/v)*dv;
dvy = -(vy/v)*dv;
// Compute velocity, including the resolved gravity vectors.
vx=vx + dt*dvx + dt*Gx;
vy=vy + dt*dvy + dt*Gy;
if (x/3>=n){
ptr[10*n+0]=x/3; // Range in yds
ptr[10*n+1]=y*12; // Path in inches
ptr[10*n+2]=-RadtoMOA(atan(y/x)); // Correction in MOA
ptr[10*n+3]=t+dt; // Time in s
ptr[10*n+4]=Windage(crosswind,Vi,x,t+dt); // Windage in inches
ptr[10*n+5]=RadtoMOA(atan(ptr[10*n+4])); // Windage in MOA
ptr[10*n+6]=v; // Velocity (combined)
ptr[10*n+7]=vx; // Velocity (x)
ptr[10*n+8]=vy; // Velocity (y)
ptr[10*n+9]=0; // Reserved
n++;
}
// Compute position based on average velocity.
x=x+dt*(vx+vx1)/2;
y=y+dt*(vy+vy1)/2;
if (fabs(vy)>fabs(3*vx)) break;
if (n>=R_CONST+1) break;
}
ptr[10*_R_CONST+1]=(double)n;
*Solution = ptr;
return n;
}
# 1 楼答案
这是运行时动态分配数组的C方式,Java等价物是
(请注意,Java不需要
sizeof(double)
因子,因为它分配的是对象,而不是字节。出于同样的原因,2048字节缓冲区缩小到256倍。)类似的,方法声明
会转化为
您指出的其他行只是访问这个double数组的元素
您没有显示
Solution
的声明,也没有询问它,但我猜Solution
是一个double **
并作为参数传递。这方面没有直接的Java等价物(尽管可以模拟);它所做的是将分配数组的地址存储到方法调用方提供的变量中