0

我正在使用 VC2010 express,遇到了一个我不太理解的结果。我的代码如下:

//

#include "stdafx.h"
#include <iostream>
#include <time.h>

using namespace std;

void main()
{
    const int gridSize = 2;
    int grid[gridSize][gridSize];

    for(int x=1; x <= gridSize; x++){
        for(int y=1; y <= gridSize; y++){
            grid[x][y] = 0;
        }

    }
    for(int i=0; i <= gridSize; i++){
        grid[i][0] = 1; // set the horizontal line to 1's
        grid[0][i] = 1; // set the vertical line to 1's
    }

    int rows = 0;
    while(rows <= gridSize){
        for(int i=0; i<=gridSize; i++){
            cout << grid[i][rows] << " ";
        }
        cout << "\n";
        rows++;
    }

    clock_t wait;
    wait = clock();
    while (clock() <= (wait + 500000));  // Wait for 500 seconds and then continue
    wait=0;
}

我期望这段代码会导致:

  • 1 1 1
  • 1 0 0
  • 1 0 0

相反,它会导致:

  • 1 1 1
  • 1 0 0
  • 1 1 0

我不明白这段代码如何用 1 填充 grid[1][2]。对此有什么想法吗?

编辑: 现在无法回答我自己的问题。但我已经解决了格子路径问题!:) 结束了这段代码来计算网格中格子路径的数量:

#include "stdafx.h"
#include <iostream>
#include <time.h>

using namespace std;

void main()
{
    const int gridSize = 3;
    int grid[gridSize+1][gridSize+1];

    for(int i=0; i <= gridSize; i++){
        grid[i][0] = 1; // set the horizontal line to 1's
        grid[0][i] = 1; // set the vertical line to 1's
    }

    for(int x=1; x <= gridSize; x++){
        for(int y=1; y <= gridSize; y++){
            grid[x][y] = grid[x-1][y] + grid[x][y-1];
        }
    }

    cout << "Amount of lattice paths for a " << gridSize << "x" << gridSize << " grid: " << grid[gridSize][gridSize];

    clock_t wait;
    wait = clock();
    while (clock() <= (wait + 500000));  // Wait for 500 seconds and then continue
    wait=0;
}

感谢您的快速回复 :)

4

1 回答 1

4

您的数组索引超出范围,例如:

for(int x=1; x <= gridSize; x++){

应该:

for(int x = 0; x < gridSize; x++){
                 ^ removed =

您应该为 index value 运行循环,是的,这种行为不端在 C 标准[0 to gridSize)中称为未定义行为。

于 2013-07-16T08:35:42.970 回答