做一个数组存储在内存中的数字计算 [英] Make an array to store the calculated numbers in memory

查看:158
本文介绍了做一个数组存储在内存中的数字计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着做一个数组来计算的数字由式存储,并把它们装入内存。这样,当数字被再次调用后,它不必重新计算。在内存造成其已。

Im trying to make an array to store calculated numbers from formula and put them into memory. So that later when the number is called up again, it doesn't have to be re-calculated. Cause its in memory already.

其计算公式为

fib(n-1) + fib(n-2);

我的code的其余部分是这样的。

The rest of my code is this

#include <iostream>
using namespace std;

// Returns the nth number in the fibonacci sequence
int fib(int n);

int main()
{
    cout << fib(46) << endl;

    system("pause");
    return 0;
}

int fib(int n)
{
    // Base cases
    if (n == 1 || n == 2) return 1;

    // Recursive cases
    return fib(n-1) + fib(n-2);
}

谢谢你们

推荐答案

如果你问如何修改给定的code,以便它可以保存价值,而不仅仅是它们打印到控制台,那么这里是一个方式:

If you are asking how to modify the given code so that it can save the values instead of just printing them to the console, then here is a way:

// Stores the numbers of the fibonacci sequence up to n inside buff
void fib(int n,int* buff);

int main()
{
    //the array to store the fibonacci series
    int buff[47];
    unsigned int i;

    //call the recursive fibonacci which will populate the array
    fib(46,buff);

    //let's also print it
    for(i = 0; i < 47; i ++)
    {
        printf("%d\n",buff[i]);
    }

    return 0;
}

// Stores the numbers of the fibonacci sequence up to n inside buff
void fib(int n,int* buff)
{

    // Base cases
    if (n == 1)
    {
         buff[n-1] = 0;
         buff[n] = 1;
         return ;
    }

    //place the recursive call after the base cases
    fib(n-1,buff);

    //and here stores the result in the buffer
    buff[n] = buff[n-1] + buff[n-2];
    return;
}

这篇关于做一个数组存储在内存中的数字计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆