斐波那契函数,用于用户输入数字

时间:2019-03-23 16:52:08

标签: c

我正在制作一个像斐波那契数列之类的程序,但是对于不超过用户提供的值的数字,例如:0到5(0、1、2、3、4)。程序需要计算数字的总和,向右移动并计算其他五个数字。它适用于斐波那契数列,但不适用于更高的数字。有谁知道如何做到这一点?

0, 1, 2, 3, 4, 10, 20, 39, 76, 149, 294...

对于0到5的值,应输出:

0, 1, 2, 3, 4, 5, 10, 15, 25, 40, 65, 105, 170, 275,

但是它输出:

@Stateless
public class A {
    @Inject
    B b;

    public update(Long id) {
        Person p = findById(id);
        b.setExecute(p.getId());
        em.refresh(p);
        p.setFirstname("john.doe");
    }
}

@Stateless
public class B {    
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void setExecute(Long personId) {
        Person p = em.find(Person.class, personId);
        p.setInExecution(true);
        p.setState(PersonState.MODIFIED);
    }
}

1 个答案:

答案 0 :(得分:1)

您需要保存最后n个值,而不仅仅是最后两个值。在您的示例中,您需要存储最后五个值。 您可以为此使用数组:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int series_number;
    int *previous_numbers;
    int marker = 0;
    int max_series_value;
    int next = 0;

    printf("Number of series: ");
    scanf("%d", &series_number);

    printf("Positive integer: ");
    scanf("%d", &max_series_value);

    printf("Series %d: \n", series_number);

    previous_numbers = malloc(sizeof *previous_numbers *series_number);
    for (int i = 0; i < series_number; i++) {
        printf("%d, ", i);
        previous_numbers[i] = i;
        next += i;
    }
    previous_numbers[marker] = next;
    marker = (marker+1) % series_number;

    while(next <= max_series_value){
        printf("%d, ", next);
        next = 0;
        for (int i = 0; i < series_number; i++) {
            next += previous_numbers[(marker+i) % series_number];
        }
        previous_numbers[marker] = next;
        marker = (marker+1) % series_number;
    }
    free(previous_numbers);

    return 0;
}