这是我的代码,甚至可以找到Fibonacci数字并添加它们:
package a;
import java.util.*;
public class A {
//this about finding Even Fibonacci numbers and adding them to sum.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int[] n = new int[t];
int[] nn = new int[t];
int i,j,sum;
for(int a0 = 0; a0 < t; a0++){
n[a0] = in.nextInt();
}
nn[0]=1;
for(i = 0 ; i<t;i++){
sum = 0;
for(j= 1;j<n[i];j++){
nn[j] = j+nn[j-1];
if(nn[j]%2==0)
{
sum += nn[j];
}
}
System.out.println(sum); //this is not printing the output
}
}
}
示例输入
2 10 100
示例输出
10 44
问题是此行System.out.println(sum);
没有打印任何内容。
有什么想法吗?
答案 0 :(得分:1)
在您的代码中
for(int a0 = 0; a0 < t; a0++){
n[a0] = in.nextInt();
}
问题是程序正在等待您输入t
整数。我不知道你想要什么价值,但是把它改成更像这样的东西
for(int a0 = 0; a0 < t; a0++){
n[a0] = 0;//But instead of 0 the actual number that you want to set for the value.
}
我希望你觉得这很有用!
答案 1 :(得分:1)
我在这里看不到问题。刚拿了代码,编译并执行它。在指定t的值并提供t输入值之后,我在控制台上看到了一个输出。
stefan@linux-3047:~$ java A
5 (t)
1 (1st of 5 values)
2 (2nd of 5 values)
3 (3rd of 5 values)
4 (4th of 5 values)
5 (5th of 5 values)
0 (System.out.println)
2 (System.out.println)
6 (System.out.println)
6 (System.out.println)
6 (System.out.println)
答案 2 :(得分:0)
这里存在多个问题。
如果t for example is 5
:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at application.A.main(A.java:25)
添加了一些System.out.println(...)
以了解如何修复它,因为我不知道您要添加的代码:
包裹申请;
import java.util.*;
public class A {
// This about finding Even Fibonacci numbers and adding them to sum.
public static void main(String[] args) {
System.out.println("Enter a number below:\n");
Scanner in = new Scanner(System.in);
int t = in.nextInt();
System.out.println("You entered..." + t+"\n");
// Arrays
int[] n = new int[t];
int[] nn = new int[t];
int i, j, sum;
// First For Loop
for (int a0 = 0; a0 < t; a0++) {
System.out.println("Enter a number a0..");
n[a0] = in.nextInt();
System.out.println("You entered ao=:" + a0+"\n");
}
nn[0] = 1;
// Second For Loop
for (i = 0; i < t; i++) {
sum = 0;
for (j = 1; j < n[i]; j++) {
nn[j] = j + nn[j - 1];
if (nn[j] % 2 == 0) {
sum += nn[j];
}
}
// this is not printing the output
System.out.println("Sum is:="+sum);
}
}
}