使用遞歸函數工作在一維諧波振盪器上,代碼在fortran中工作並嘗試轉換爲C++以學習新的語法。一維諧波振盪器遞歸函數,可能Infinit循環,C++語法
我修復了迄今爲止通過google搜索到的所有通知錯誤,但仍然沒有得到結果。該計劃看似永遠運行,沒有公佈結果。
我認爲可能的答案可能是它沒有被計算出來或有一些infinit循環,因爲我的循環或調用函數中的語法問題?但我沒有看到它,也沒有發現它們的錯誤。
有關爲何該程序無法正常工作的任何建議?
//
// main.cpp
// 1-d HO
//
// Created by Grant Metheny on 3/2/16.
// Copyright (c) 2016 Grant Metheny C++ Codes. All rights reserved.
//
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cmath>
#include <math.h>
using namespace std;
int i = 0;
int n = 0;
double x = 1.;
double xmax = 5;
double imax = 1000;
double wavefunc = 0;
double fact = 1;
double hpol = 1;
double wf0 = 1;
double wf1 = 1;
double wf2 = 1;
double wf3 = 1;
double wf4 = 1;
double wf5 = 1;
double wf6 = 1;
double wavefunction(int n, double x)
{
return wavefunc = pow(2.0,-(n*.5)) * pow(M_PI,.25) * exp(-(.5*pow(x,2.0)));
}
double factorial(int n)
{
for (i = 0; i <= n; i++)
if (i == 0)
fact = 1.;
else
fact = fact * i;
return fact;
}
double hermite(int n, double x)
{
for (i = 0; i <= n; i++)
if (i==1)
hpol = 1.0;
else if (n==1)
hpol = 2*x;
else
hpol = 2*x*hermite(n-1,x) - 2*(n-1)*hermite(n-2,x);
return hpol;
}
double dx = 2*xmax/imax;
int main(int argc, const char * argv[]) {
for (i=0; i <= imax; i++) {
x = 5. - dx*i;
n = 0;
wf0 = hermite(n,x) * wavefunction(n,x) * pow(factorial(n),(-(.5)));
n = 1;
wf1 = hermite(n,x) * wavefunction(n,x) * pow(factorial(n),(-(.5)));
n = 2;
wf2 = hermite(n,x) * wavefunction(n,x) * pow(factorial(n),(-(.5)));
n = 3;
wf3 = hermite(n,x) * wavefunction(n,x) * pow(factorial(n),(-(.5)));
n = 4;
wf4 = hermite(n,x) * wavefunction(n,x) * pow(factorial(n),(-(.5)));
n = 5;
wf5 = hermite(n,x) * wavefunction(n,x) * pow(factorial(n),(-(.5)));
n = 6;
wf6 = hermite(n,x) * wavefunction(n,x) * pow(factorial(n),(-(.5)));
cout <<"I="<< i <<"X="<< x <<"WF0="<< wf0<<"WF1=" << wf1; // wf2, wf3, wf4, wf5, wf6
}
return 0;
}
如果你想學習C++,我建議你找一本很好的初學者書,例如來自[The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-書指南和列表)。 –