除以 0 时出错但代码中没有零
error with deviding by 0 but no zero in the code
我正在尝试用 java 解决 Project Eleur 编码问题(斐波那契数列中的每个新项都是通过添加前两个项生成的。从 1 和 2 开始,前 10 个项将 be:1, 2, 3, 5, 8, 13, 21, 34, 55, 89 考虑斐波那契数列中不超过四百万的项,求偶数项之和。) I做了这个代码
public class JavaApplication15 {
public static void main(String[] args) {
int a1=1;
int a2=2;
int a3;
int aux;
int sum=3;
a3=3;
while(a3<=4000000){
a3=a1+a2;
aux=a2;
a2=a3;
a1=aux;
if(a3%0==0){
sum+=a3;
}
}
System.out.println("the sum is"+sum);
}
我不知道它是否会显示正确的答案但是我在编译代码时得到的错误是线程中的异常 "main" java.lang.ArithmeticException: / by zero
正如评论所指出的,您会得到一个 ArithmeticException,因为 % (modulo) returns 除法的余数,换句话说,它执行除法。
这就好像你会写 a3/0,同样的例外。
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms
我想您可能想对偶数斐波那契值求和。对于这种情况,模数是正确的操作数,但是您必须除以 2 并检查余数是否为 0。
我正在尝试用 java 解决 Project Eleur 编码问题(斐波那契数列中的每个新项都是通过添加前两个项生成的。从 1 和 2 开始,前 10 个项将 be:1, 2, 3, 5, 8, 13, 21, 34, 55, 89 考虑斐波那契数列中不超过四百万的项,求偶数项之和。) I做了这个代码
public class JavaApplication15 {
public static void main(String[] args) {
int a1=1;
int a2=2;
int a3;
int aux;
int sum=3;
a3=3;
while(a3<=4000000){
a3=a1+a2;
aux=a2;
a2=a3;
a1=aux;
if(a3%0==0){
sum+=a3;
}
}
System.out.println("the sum is"+sum);
}
我不知道它是否会显示正确的答案但是我在编译代码时得到的错误是线程中的异常 "main" java.lang.ArithmeticException: / by zero
正如评论所指出的,您会得到一个 ArithmeticException,因为 % (modulo) returns 除法的余数,换句话说,它执行除法。
这就好像你会写 a3/0,同样的例外。
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms
我想您可能想对偶数斐波那契值求和。对于这种情况,模数是正确的操作数,但是您必须除以 2 并检查余数是否为 0。