Program to generate iterations

纵然是瞬间 提交于 2019-12-13 03:35:28

问题


I have set myself a task to code this algorithm, however, since i haven't had a full experience in C, I was hoping there might be an easier method.

Ok, Take 2 numbers, a , b

We take the sum of these and add to the sequence, then add on the second term.

So we get a , b , a+b , b

For the next term, we take the 2nd and 3rd values (Before we did 1st and 2nd) and do it again.

so we now get

a , b , a+b , b , a +2b , a+b 

(continued) a+2b , b , a+3b , a+2b , 2a+3b , a+b

This continues on until whenever, it does not have to have an input.

Basically my algorithm comes as: The next a was the previous b , the Next b is the previous a + the previous b.

However, i cannot code this in c using general methods, since it will work from the appended values given to the sequence, rather than the 1st , 2nd , 3rd values etc.

I was thinking that this could be done instead by writing to a file and scanning line by line for the nth number. However, i think i am way over complicating this.

Is there a way that i can take an nth value from this sequence?

Input: a = 1 , b =1 . Expected output: 1, 1 ,2 ,1 3, 2 , 3 ,1 ,4 3, 5 , 2


回答1:


You should use arrays, it is not difficult and it will be much better than using files. Read some documentation and you should be able to use them in 5min.

An array is just a sequence of things, integers in your case. You probably can do something like this:

int main () {
    int array[MAX];
    array[0] = 1;
    array[1] = 1;
    // Print the starting values:
    printf("%d\n%d\n", array[0], array[1]);

    // The loop is controlled by i, increased in steps of 2.
    // j keeps the sequence of 1,2; 2,3; 3,4... used for the sum
    for (int i = 2, j = 0; i < MAX; i+=2, j++) {
        array[i] = array[j] + array[j+1];
        array[i+1] = array[j+1];
        printf("%d\n%d\n", array[i], array[i+1]);
    }
    return 0;
}



回答2:


"The next a was the previous b , the Next b is the previous a + the previous b." If you're just trying to get the nth value, you can use the 4 variables you just described (this could be optimized, but might as well code to match the description):

int n = 12;
int i;
int preva = 1;
int prevb = 1;
int nexta;
int nextb;
    for(i = 2; i < n; i += 2){
        nexta = prevb;
        nextb = preva + prevb;
        preva = nexta;
        prevb = nextb;
    }
    if(i == n)
        /* output prevb */
    else
        /* output preva */


来源:https://stackoverflow.com/questions/27443601/program-to-generate-iterations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!