search

Home  >  Q&A  >  body text

c++ - 打印杨辉三角形为什么在for循环的条件中搞自增自减就错误

vs执行直接显示程序结束运行

#include<iostream>
using namespace std;
int main()
{
    int row, col, a[10][10];
    for (row = 0; row < 10; row++)
    {
        a[row][0] = 1; a[row][row] = 1;
        for (col = 1; col <= (++row); col++)
        {
            a[row][col] = a[row - 1][col - 1] + a[row - 1][col];
        }
        for (col = 0; col <=(--row); col++)
        {
            cout << a[row][col] << "\t";
        }
        cout << endl;
    }
    return 0;
}
//问题在col <= (++row)和col <=(--row)
//把++row移到col = 1和--row移到col=0之前就没问题

PHPzPHPz2804 days ago587

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 15:03:43

    Don’t you know how to cross the array boundary?

    for (row = 0; row < 10; row++)
    When row = 9

    for (col = 1; col <= (++row); col++)
    First ++ col maximum value 10
    a[10][10] index range 0-9


    Your original way of writing is an infinite loop

    col <= (++row)

    Every time col++ but ++row is used, then the condition will always be satisfied

    reply
    0
  • Cancelreply