c++ - 打印杨辉三角形为什么在for循环的条件中搞自增自减就错误
PHPz
PHPz 2017-04-17 15:01:43
0
1
565

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之前就没问题

PHPz
PHPz

学习是最好的投资!

reply all(1)
Ty80

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!