java - 欧拉项目编号 2 : Even Fibonacci numbers 的问题

标签 java algorithm

这是我的代码:

public static void main(String[] args) {
    int f=1;//first number
    int s=2;//second number
    int fin=0;//final answer
    int x;
    System.out.println("1\n2");
    for (x=3; x<4000000; x=f+s){
        System.out.println(x);
        f=s;
        s=x;
        if (x%2==0){
            fin+=x;
        }
    }
    System.out.println("Sum of all even number: "+fin+2);
}

出于某种原因,当实际答案是 4613732 时,我得到的是 46137302 作为我的最终答案。我不确定为什么我的答案是实际答案的十倍。

最佳答案

您偶然发现了 java 的漂​​亮字符串连接。以下作品:

System.out.println("Sum of all even number: " + (fin+2));

您必须明确地对数字求和。否则 Java 继续从左到右对值求和:您的字符串 + 实际数字,给出类似于 "Sum of all even number: 4613730" 的内容。然后附加 2 给出 “所有偶数的总和:46137302”。但是您想先对数字求和:您需要将它们包装在 () 中。

关于java - 欧拉项目编号 2 : Even Fibonacci numbers 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34533985/

相关文章:

java - Android RecyclerView Adapter 在单元测试中给出 null

java - 在java中读取时跳过文本文件的某些部分

c - 如何找到 "product of numbers"的因子数

algorithm - 将 2D 点划分为 N 个区域,每个区域有 K 个相邻点

java - Android OpenGL ES 2.0 VBO

java - Solr : Always seeking for a core named "collection1"

java - 如何在甘特图中显示每个任务的信息

java - 二十一点极小极大算法

python - 排列矩形的顶点

java - treeMap中entrySet的时间复杂度是多少