无限递归循环C

时间:2018-03-05 16:39:27

标签: c recursion

本周我们一直在学习C中的递归与迭代,我们需要制作一个程序,递归地确定由a,ar,ar ^ 2,...定义的几何序列的第n项的值。 .ar ^(nq)。 在大多数情况下,我认为我已经弄明白了,因为它似乎显示每次运行的正确值,但是当测试值达到零时它无法破坏递归。此外,如果可能的话,可以更好地解释递归,并且在迭代时优先考虑递归的一些例子,因为我仍在努力解决这个问题。     // 2/20/2018     //实验6解决方案Page 369 PE 4 B

//including libraries to be used
#include <stdio.h>
#include <math.h>

int main() {
    //Function prototype
    double goAnswer(int *, double, double, double, double *, int);

    //Declaring variables
    int nValue = 0;
    double ratio = 0;
    double firstTerm = 0;
    double answer = 0;
    double addedAnswer = 0;
    int count = 1;

    //Setting up to ask for each value
    printf("Please enter in the value of n: ");
    scanf("%d", &nValue);
    printf("Please enter in the ratio you'd like to use: ");
    scanf("%lf", &ratio);
    printf("Please enter in the first term to use: ");
    scanf("%lf", &firstTerm);
    addedAnswer = goAnswer(&nValue, ratio, firstTerm, answer, &addedAnswer, 
count);

    //Printing out the value of the first nth terms
    printf("The value of all terms added together is: %lf\n", addedAnswer);

    return 0;
}

//function header
double goAnswer(int *nValue, double ratio, double firstTerm, double answer, 
double *addedAnswer, int count) {

    if (nValue == 0){
        return 0;
    }
    else{ //This part calculates the answer, prints the value to the screen, 
adds the answer to a running sum, decreases the nValue by one and calls the 
function again with the lower nValue
        answer = firstTerm * pow(ratio, count);
        printf("The value of term %d is: %lf\n", count, answer);
        printf("This is the nValue: %d \n", *nValue);
        *addedAnswer += answer;
        nValue -= 1;
        return (goAnswer(nValue, ratio, firstTerm, answer, addedAnswer, 
(count + 1)));
    }

}

0 个答案:

没有答案
相关问题