递归/迭代函数 [英] Recursive/iterative functions

查看:133
本文介绍了递归/迭代函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很难创建一个函数,使用迭代和递归找到1和用户输入的数字之间的所有偶数的总和。程序指南需要一个函数来解决这三种方式:

I'm having a bit of a hard time creating a function, using iteration and recursion to find the sum of all even integers between 1 and the number the user inputs. The program guidelines require a function to solve this three ways:


  1. 一个公式

  2. li>
  3. 递归

这是我到目前为止:

#include <iostream>
#include <iomanip>
#include <cstdlib>

using namespace std;

void formulaEvenSum(int num, int& evenSum)
{
    evenSum = num / 2 * (num / 2 + 1);
    return;
}

void loopEvenSum(int num, int& evenSum2)
{

}


int main()
{
    int num, evenSum, evenSum2;

     cout << "Program to compute sum of even integers from 1 to num.";
     cout << endl << endl;

     cout << "Enter a positive integer (or 0 to exit): ";
     cin >> num;

     formulaEvenSum(num, evenSum);
     loopEvenSum(num, evenSum2);

     cout << "Formula result = " << evenSum << endl;
     cout << "Iterative result = " << evenSum2 << endl;

     system("PAUSE");
     return 0;

}


推荐答案

找到偶数的和如下所示。

Using iteration to find the sum of even number is as given below.

void loopEvenSum(int num, int &evenSum2)
{
    evenSum2=0;
    for (i=2;i<=num;i++)
    {
        if(i%2==0)
            evenSum2+=i;
    }
}

下面的代码虽然不是最高效的,一个想法如何写一个递归函数。

The following code though not the most efficient can give you an idea how to write a recursive function.

void recursiveEvenSum(int num,int &evenSum3,int counter)
{
    if(counter==1)
        evenSum3=0;
    if(counter>num)
        return;
    if(counter%2==0)
        evenSum3+=counter;
    recursiveEvenSum(num,evenSum3,counter+1);
}

现在你可以调用recursiveEvenSum b
$ b

Now you can call recursiveEvenSum(...) as

int evenSum3;
recursiveEvenSum(num,evenSum3,1);

这篇关于递归/迭代函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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