我習慣於在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