2013-05-04 62 views
0

我已经做了一个搜索,但没有任何可用的代码在Java中,因此我写我自己的,我遇到了一些问题。我实际上从C++源代码中获得了这些代码,并努力将其转换为可行的java程序。在JAVA中的拉格朗日插值

http://ganeshtiwaridotcomdotnp.blogspot.sg/2009/12/c-c-code-lagranges-interpolation.html

public static void main(String[] args) { 

    int n; 
    int i, j; 
    int a; 
    int x[] = null; 
    int f[] = null; 
    int sum = 0; 
    int mult; 
    Scanner input = new Scanner(System.in); 
    System.out.println("Enter number of point: "); 
    n = input.nextInt(); 

    System.out.println("Enter value x for calculation: "); 
    a = input.nextInt(); 

    for (i = 0; i < n; i++) { 

     System.out.println("Enter all values of x and corresponding functional vale: "); 
     x = input.nextInt(); 
     f = input.nextInt(); 
    } 

    for (i = 0; i <= n - 1; i++) { 
     mult = 1; 
     for (j = 0; j <= n - 1; j++) { 

      if (j != i) { 
       mult *= (a - x[j])/(x[i] - x[j]); 

      } 
      sum += mult * f[i]; 
     } 

    } 
    System.out.println("The estimated value of f(x)= " + sum); 

} 
+0

在源上方他创建了一个大小为[10] 的数组,然而我应该如何在java编码中实现这个 – newbieprogrammer 2013-05-04 14:10:15

+0

所以你不知道如何在java中创建一个数组? – Kevin 2013-05-04 14:12:01

+0

自己编写算法通常比翻译别人做的更容易:你不会继承他的错误。 – dasblinkenlight 2013-05-04 14:13:16

回答

0
int x[] = null; 
int f[] = null; 
... 
for (i = 0; i < n; i++) { 
    .... 
    x = input.nextInt(); 
    f = input.nextInt(); 
} 

看起来不够清晰。

x = new int[n]; 
f = new int[n]; 

某处后:简单地对于x和f创建数组实例

n = input.nextInt(); 

之前上述for环,以及修改for体:在C++

... 
x[i] = input.nextInt(); 
f[i] = input.nextInt(); 
+0

他正在给一个整数赋一个数组,他显然意味着x [i] = input ...等 – arynaq 2013-05-04 14:26:24