从数组中打印特定值

时间:2015-04-27 03:11:19

标签: java arrays

如何为任何特定索引打印斐波纳契函数的值,比如n,其中n是提供的参数值?

1 import java.util.Arrays;
2 
3 public class Fibonacci {
4
5 public static void main(String[] args) {
6   int n = Integer.parseInt(args[0]);
7   if(n<3){
8       return;
9   }else{
10      int[] f = new int[n];
11      f[0] = 1;
12      f[1] = 1;
13      int i= 0;
14      for(i=2; i<f.length; i++){
15          f[i]= f[i-1]+ f[i-2];
16      }
17      System.out.println(f[i]);
18  }
19  
20 }
21
22 }

4 个答案:

答案 0 :(得分:1)

我相信你遇到的问题是System.out.println(f[i]);

在此位置,i将等于f[]的长度。如果您使用i作为索引,则它将超出范围。

如果要打印最后一个值,则应为System.out.println(f[i-1]);

答案 1 :(得分:1)

您正在打印#define MAXS 10 #define MAXBUF 200 char buff[MAXBUF] = {0}; char studno[MAXS] = {0}; char courseno[MAXS] = {0}; char oldstudno[MAXS] = {0}; while(fgets(buff, MAXBUF - 1, fp) != NULL){ /* safely remove trailing newline or character return */ size_t len = strlen (buff); while (len > 0 && (buff[len-1] == '\n' || buff[len-1] == '\r')) buff[--len] = 0; tokenptr = strtok(buff,","); /* first token on ',' */ while (tokenptr != NULL) { size_t slen = strlen (tokenptr); /* get tokenptr length */ if (slen > MAXS - 1) { strncpy (studno, MAXS - 1, tokenptr); /* copy max of 9 char */ studno[MAXS - 1] = 0; /* null-terminate */ } else strcpy (studno, tokenptr); /* just copy */ if (!(tokenptr = strtok(NULL,","))) /* get courseno pointer */ break; size_t clen = strlen (tokenptr); /* get tokenptr length */ if (clen > MAXS - 1) { strncpy (courseno, MAXS - 1, tokenptr); /* copy max of 9 char */ studno[MAXS - 1] = 0; /* null-terminate */ } else strcpy (courseno, tokenptr); /* just copy */ if ((slen + strlen (oldstudno)) < MAXS) /* confirm length OK */ strcat(oldstudno,studno); else fprintf (stderr, "error: string lengths too great to concatenate.\n"); } ,这将为您提供f[i],因为那时ArrayIndexOutOfBoundsException的值超过了数组i的边界。

一个简单的解决方法是通过采用如下单独的变量来打印数组:

f

如果要打印任何特定索引,则可以在打印前进行一次边界检查:

int n = Integer.parseInt(args[0]);
if(n<3){
    return;
}else{
    int[] f = new int[n];
    f[0] = 1;
    f[1] = 1;
    int i= 0;
    for(i=2; i<f.length; i++){
        f[i]= f[i-1]+ f[i-2];
     }

     for (int j=0;j<n;j++){
     System.out.println(f[j]);
    }
}

答案 2 :(得分:1)

您的代码基本上没问题,但我在回复中调整了一些内容:

public static void main(String[] args) {
    int n = Integer.parseInt(args[0]);
    if (n < 0) {
        System.out.println("Cannot computer Fib() of a negative number.");
        return(0);
    } else if (n < 3) {
       System.out.println("Fib[" + n + "] = 1");
    } else {
        int[] f = new int[n];
        f[0] = 1;
        f[1] = 1;
        for(int i=2; i < f.length; ++i) {
            f[i] = f[i-1]+ f[i-2];
        }
        System.out.println("Fib[" + n + "] = " + f[n - 1]);
    }
}

答案 3 :(得分:0)

我认为以递归的方式使Fibonachi变得更好:

public int fib(int n) {
    if (n < 2) {
       return n;
    }
    else {
       return fib(n-1)+fib(n-2);
    }
    System.out.println(n);
}