gpt4 book ai didi

c++ - 函数返回数组但输出不符合预期

转载 作者:行者123 更新时间:2023-11-30 03:47:24 24 4
gpt4 key购买 nike

我遇到的问题是我试图从函数 EnterNumber() 返回一个数组并将其显示在主体中,但它的出现相当疯狂。我通过调试器进行了调试,调试器中的数字是正确的,只是在打印到屏幕上时不正确。

Here's a shot of the debugger after returning from the function

Here's a shot of what it prints

我意识到我的程序中有一个全局 const int,但它得到了我的教授的批准,他希望我们这次只为这个程序这样做。

只是想知道为什么打印不正确。谢谢。

#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";
}

最佳答案

这个:

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

应该是这样的:

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

您重复打印了刚好超出数组末尾的数字。

关于c++ - 函数返回数组但输出不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33687219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com