我习惯于在Fortran中编写程序(这是f90),但我需要用C++编写程序。我很困惑如何从C++函数传递多维数组。举个例子,我想在子程序中读取XYZ格式的原子坐标列表,然后将坐标传递给主程序。在C++中为Fortran程序员传递多维数组
这是用Fortran:
program findcenterofmass
character*2 atm(1000)
integer ttl
real*8 crd(1000,3)
call getxyz(atm,ttl,crd)
call centerofmass(ttl,crd)
end
subroutine getxyz(element,atomcount,coord)
character*2 element(1000)
integer atomcount
real*8 coord(1000,3)
open(file='test.xyz',unit=1)
read(1,*) atomcount
read(1,*)
do i=1,atomcount
read(1,*) element(i),(coord(i,j),j=1,3)
enddo
close(unit=1)
end
subroutine centerofmass(atomcount,coord)
integer atomcount
real*8 coord(1000,3)
real*8 x,y,z
do i=1,atomcount
x=x+coord(i,1)/atomcount
y=y+coord(i,2)/atomcount
z=z+coord(i,3)/atomcount
enddo
write(*,*) 'Center of mass is x: ',x,' y:',y,' z:',z
end
此处读取的文件是一个非常简单的CO2分子:
3
C 0.0 0.0 0.0
O -1.4 0.0 0.0
O 1.4 0.0 0.0
所以我需要做的在C此相同的步骤++和一部分似乎 最令人困惑的是读取坐标到多维 数组,然后将数组传回主程序。
这里的C++(这有错误) - 任何帮助将不胜感激!
#include <stdio.h>
#include <iostream>
#include <string>
#include <sstream>
void readxyz(double& x);
int main() {
double x[100][3];
readxyz(double& x);
std::cout << " x " << x[0][0] << "\n";
return 0;
}
void readxyz(double& coord[][3])
{
int i,j,k;
int ttl;
int MAXATOM=1000;
int MAXLINE=72;
char atoms[MAXATOM][2];
long double coord[MAXATOM][3];
char s[MAXLINE];
const char* filename="test.xyz";
using namespace std;
cout.precision(12);
FILE *fp = fopen(filename,"r");
fgets(s,MAXLINE,fp);
std::stringstream stream(s);
stream >> ttl;
fgets(s,MAXLINE,fp);
for (i = 0; i < ttl; i++) {
fgets(s,MAXLINE,fp);
std::stringstream stream(s);
stream >> atoms[i] >> coord[i][0] >> coord[i][1] >> coord[i][2];
}
}
@Anycorn:不_really_相关,如Fortran语言在这种情况下是user11255566想重新写在C++ ... – sarnold 2012-01-02 02:53:01
节目我不好的想法,他想通过c和f90之间的数组 – Anycorn 2012-01-02 02:58:22
相关[常见问题](http:// stackoverflow。com/questions/4810664 /) – fredoverflow 2012-01-02 13:07:47