【发布时间】:2014-03-16 22:42:25
【问题描述】:
我正在制作一个递归数组函数,它计算数字并将它们加在一起,然后在递归函数中返回它们。该函数似乎确实有效,但我最初输入到数组中的数字是 1,2,3,4,5 但程序告诉我这些数字是 49、50、51、52、53... 非常困惑为什么这可能会发生,任何帮助或见解将不胜感激。谢谢!
#include <iostream>
using namespace std;
const int SIZE = 5;//size of array
int sum(int [], int);//recursive function
int main()
{
int sumArray[SIZE] = { '1', '2', '3', '4', '5'};//array with predetermined values
cout << sumArray[0] << endl;//49
cout << sumArray[1] << endl;//50
cout << sumArray[2] << endl;//51
cout << sumArray[3] << endl;//52
cout << sumArray[4] << endl;//53
cout << sum(sumArray, SIZE) << endl;//displays the amount 255 (5 elements added)
system("pause");
return 0;
}
int sum(int sumArray[], int size)
{
if (size == 1)
return sumArray[size - 1];
else
{
cout << size << endl;
return sumArray[size - 1] + sum(sumArray, size - 1);
}
}
【问题讨论】:
标签: c++ arrays function recursion