سؤال

This is my first question so don't be mad at me, if I did something wrong. I have to make a C++ program which returns an element from a selected row, for example:

Triangle 4 0 1 2 3

should return elements: 0, 1, 2 and 3 from row number 4, but it returns strange things, like:

Element 0: 1
Element 1: 10179988
Element 2: 50792126
Element 3: 91425820

I have no idea why
Here's my code:

#include <cstdlib>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

class Pascal {
    private:
        int *tab;

    public:
        Pascal(int n) throw(string) {
            if (n < 0)
                throw (string)"";

            tab = new int[n+1];

            for(int i = 1; i <= n; i++) {
                for(int k = i; k >=0; k--) {
                    if (k - 1 >= 0)
                        tab[k] += tab[k-1];
                    else
                        tab[k] = 1;
                }
            }
        };

    int element(int m) {
        return tab[m];
    }
};

int main(int argc, char* argv[]) {
        int n = 0, m = 0, elem = 0;

        try {
            n = strtol(argv[1], NULL, 0);
            Pascal *row;

            for(int i = 2; i < argc; i++) {
                try {
                    m = strtol(argv[i], NULL, 0);
                    row = new Pascal(n+1);

                    if (m <= n && m >= 0) {
                        elem = row->element(m);
                        cout << "Element " << m << ": "<< elem << endl;
                    } else
                        cout << m << " - bad element index" << endl;

                } catch (string ex) {
                    cout << argv[i] << " - bad element index!" << endl;
                    continue;
                }

                delete[] row;
            }
        } catch (string e) {
            cout << argv[1] << " - bad row index!" << endl;
            return 0;
        }
    }

I'll be grateful for any answer

هل كانت مفيدة؟

المحلول 2

Try

tab = new int[n+1];

for(int i = 0; i <= n; i++) {
    tab[i] = 1;
    for(int k = i; --k > 0; )
        tab[k] += tab[k-1];
}

نصائح أخرى

           tab = new int[n+1];

            for(int i = 1; i <= n; i++) {
                for(int k = i; k >=0; k--) {
                    if (k - 1 >= 0)
                        tab[k] += tab[k-1];
                    else
                        tab[k] = 1;
                }
            }

first iteration:  i=1, k=1, tab[1]+=tab[0];
second iteration: i=1, k=2, tab[2]+=tab[1]; 

So you are not properly initializing your array, you are simply adding whatever values are in memory...

I think replacing if (k - 1 >= 0) with if (k - 1 > 0) should solve your problem

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top