为什么递归函数打印正确的值但是调用之后的cout语句没有?

时间:2014-08-04 07:56:00

标签: c++

为什么递归函数中的cout语句是打印15,尽管递归函数之外的那个(在main中)正在打印0.我设置num = recursive_function()。

更新:我是一个菜鸟,并在上述功能中返回0。问题得到解决。谢谢。

#include <iostream>
#include <string>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int sumNumbers(int sum, vector<int> numbers, int count) 
{
    if ( count == numbers.size() ) {
        cout << "The sum of the numbers in the file is: " << sum << endl; - 1st cout statement
        return sum;
    }

    return sumNumbers(sum + numbers[count], numbers, count + 1);


}

int main(int argc, char* argv[]) 
{
    vector<int> numbers;
    int numElements = 0;; 
    int sum;

    string fileName = argv[2];

    ifstream ifile(fileName);

    if( ifile.fail() ) {    
        cout << "The file could not be opened. The program is terminated." << endl;
        return 0;
    }

    int new_number;

    while (ifile >> new_number) numbers.push_back(new_number);

    sum = sumNumbers(sum, numbers, 0);

    cout << "The sum of the numbers in the file is: " << sum << endl; - 2nd cout statement

    return 0;
}

输出:

The sum of the numbers in the file is: 15
The sum of the numbers in the file is: 0

1 个答案:

答案 0 :(得分:1)

这是因为您的sumNumbers方法在其末尾有return 0

只需删除它,然后将return sumNumbers(sum + numbers[count], numbers, count + 1);放在最后。