【问题标题】:different numbers output from an array than input using recursive function?使用递归函数从数组输出的数字与输入的数字不同?
【发布时间】: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


    【解决方案1】:

    您实际上被放入了数字的 ASCII 码数组中:'1' 实际上是一个 char,代码为 49,它被转换为 int 49。写法如下:

    int sumArray[SIZE] = { 1, 2, 3, 4, 5 };
    

    这称为implicit conversion - 查看“整体促销”部分。

    【讨论】:

      猜你喜欢
      • 2012-12-14
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 2021-01-05
      • 2021-07-21
      • 1970-01-01
      • 2016-10-05
      相关资源
      最近更新 更多