从数组打印时,零未显示为0

Zero not displaying as 0 when printing from array

本文关键字:显示 数组 打印      更新时间:2023-10-16

除了秒数等于4或4的倍数外,其他一切都按预期进行。在这种情况下,秒的0显示为零以外的值。

请向我解释为什么会发生这种情况。

当秒数=3时,输出为:

Please enter the height of the bridge (meters): 100
Please enter the time the watermelon falls: 3
Time Falling (seconds) Distance Falling (meters)
*************************************************
0   0
1   4.9
2   19.6
3   44.1

当秒=4时,输出为:

Please enter the height of the bridge (meters): 100
Please enter the time the watermelon falls: 4
Time Falling (seconds) Distance Falling (meters)
*************************************************
1117572301  0
1   4.9
2   19.6
3   44.1
4   78.4

代码:

#include <iostream>
using namespace std;
int main()
{
//declare variables
int seconds, heightBridge, count;
float heightWatermelon, maxFall;
const float gravity = 9.8;
//get variables from user
cout << "Please enter the height of the bridge (meters): ";
cin >> heightBridge;
cout << "Please enter the time the watermelon falls: ";
cin >> seconds;
//declare array's
int secondsArray[seconds];
float heightWatermelonArray[seconds];
for (count = 0; count <= seconds; count++)
    {
    heightWatermelon = 0.5 * gravity * count * count;
    secondsArray[count] = count;
    heightWatermelonArray[count] = heightWatermelon;
    }
//create heading
cout << "Time Falling (seconds) Distance Falling (meters)n";
cout << "*************************************************n";
//calculate max fall distance
maxFall = 0.5 * gravity * seconds * seconds;
//display data
for (count = 0; count <= seconds; count++)
    {
    if (maxFall > heightBridge)
        {
        cout << "Warning - Bad Data: The distance fallen exceeds the "
             << "height of the bridge" << endl;
        break;
        }
    else
        cout << secondsArray[count] <<  "t"
             << heightWatermelonArray[count] << endl;
    }

return 0;
}

您使用的是从0seconds(包括)的索引,因此您的数组必须声明为

int secondsArray[seconds+1];
float heightWatermelonArray[seconds+1];

(似乎只有才能使用较小的值,您的代码实际上是在调用未定义的行为)。

您声明您的数组如下:

//declare array's
int secondsArray[seconds];
float heightWatermelonArray[seconds];

然后在以下循环中访问:

for (count = 0; count <= seconds; count++)

当您声明一个长度为seconds的数组时,这会分配一个元素数为seconds的数组。因为数组是零索引的,这意味着索引0..(seconds-1)是有效的。您的循环将从0..seconds开始,因此将导致溢出。要修复此问题,只需将<=更改为<即可。

另一个解决方案是按照Zeta下面所说的调整数组的大小。在这种情况下,只需将阵列规范更改为以下内容:

//declare array's
int secondsArray[seconds+1];
float heightWatermelonArray[seconds+1];

然后你可能会想,为什么你会得到一个奇怪的数字,而不是零。因为在x86上(我假设您在x86上),堆栈向下增长,所以heightWatermelonArray将直接在内存中的secondsArray之前。当你写入heightWatermelonArray[seconds]时(即在heightWatermelonArray的末尾,你会溢出数组,然后进入下一个内存位。在这种情况下,该内存将是secondsArray的第一个元素,因此你会损坏内存。