简体   繁体   English

函数返回Array,但输出不符合预期

[英]Function returns Array but output is not as expected

The issue I'm having is I'm trying to return an array from the function EnterNumber() and display it in the main, but its coming out fairly crazy. 我遇到的问题是我正在尝试从函数EnterNumber()返回一个数组并将其显示在主体中,但是它的出现相当疯狂。 I went through with the debugger and the numbers are correct in the debugger, just not correct in once it prints to the screen. 我经历了调试器,调试器中的数字是正确的,只是在打印到屏幕上时数字是不正确的。

这是从函数返回后的调试器的快照

这是打印出来的照片

I realize there's a global const int in my program, but it was sanctioned by my professor who wanted us to do it just this time for this program. 我意识到我的程序中有一个全局常量,但是我的教授批准了它,希望我这次为这个程序做。

Just looking for a nudge on why its printing incorrectly. 只是想找寻为什么其打印不正确。 Thank you. 谢谢。

#include <iostream>

using namespace std;

void EnterNumber(int Number[]);

const int SIZE=20;

int main()
{
    int LargeNumber1[SIZE];
    int LargeNumber2[SIZE];

    for (int Counter1=0; Counter1<=19; ++Counter1)//zeros arrays out
    {
        LargeNumber1[Counter1]=0;
        LargeNumber2[Counter1]=0;
    }

    EnterNumber(LargeNumber1);

    for (int Counter2=0; Counter2<=19; ++Counter2)//display array 1 contents
    {
        cout << LargeNumber1[SIZE];
    }

    cout << "\n\n";

    EnterNumber(LargeNumber2);

    for (int Counter2=0; Counter2<=19; ++Counter2)//display array 2 contents
    {
        cout << LargeNumber2[SIZE];
    }

}

void EnterNumber(int Number[])
{
    int TemporaryArray[SIZE];
    int PlaceCounter;

    char Storage;

    PlaceCounter=0;

    for (int Counter1=0; Counter1<=19; ++Counter1)//zeros arrays out
    {
        TemporaryArray[Counter1]=0;
        Number[Counter1]=0;
    }

    cout << "Please enter a large number --> ";

    cin.get(Storage);

    while (Storage!='\n' && PlaceCounter<SIZE)//puts number in temp array - left aligned
    {
        TemporaryArray[PlaceCounter]=(Storage-'0');
        ++PlaceCounter;
        cin.get(Storage);
    }

    --PlaceCounter;//decrement one to get it to work properly with element style counting, else, extra zero at end

    for (int A=SIZE-1; PlaceCounter>=0; A--, PlaceCounter--)//transfers old array into new array, right aligned
    {
        Number[A]=TemporaryArray[PlaceCounter];
    }

    cout << "\n";
}

This: 这个:

for (int Counter2=0; Counter2<=19; ++Counter2)
{
    cout << LargeNumber1[SIZE];
}

should be this: 应该是这样的:

for (int Counter2=0; Counter2<SIZE; ++Counter2)
{
    cout << LargeNumber1[Counter2];
}

You were repeatedly printing a number that was just beyond the end of the array. 您反复打印的数字刚好超出数组末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM