简体   繁体   中英

How to have multiple int values in every element in a one dimensional array?

i want to fill one one dimensional array with two int values.

When i run my code without brackets around the values i get only the frist int and when i run it with brackets around the values i get only the second int.

Output should be like x/y

thank you for your time.

int main()
{
    cBruch cBruch[7];

    cBruch[0] = (3, 4);
    cBruch[1] = (24, -6);
    cBruch[2] = -5, -3;
    cBruch[3] = -14, 22;
    cBruch[4] = 21, 45;
    cBruch[5] = 7, -9;
    cBruch[6] = 2, 3;

    for (int i = 0; i < 7; i++)
    {
        cBruch[i].ausgabe();
    }

    return 0;
}

.h

class cBruch
{
private:
    int zaehler;
    int nenner;

    int ggt(int a, int b);
    void kuerzen();

public:
    cBruch(int zaehler_in = 0, int nenner_in = 1);
    ~cBruch();

    void ausgabe(); //output
};

.cpp

cBruch::cBruch(int zaehler_in, int nenner_in)
{
    zaehler = zaehler_in;
    nenner = nenner_in;

    cout << "Konstruktor Zaehler = " << zaehler << " Nenner = " << nenner << endl;
}

cBruch::~cBruch()
{
    cout << "Destruktor Zaehler = " << zaehler << " Nenner = " << nenner << endl;
}

void cBruch::ausgabe()
{
    cout << "Bruch: " << zaehler << "/" << nenner << "\tGleitkommazahl: "<< double(zaehler) / nenner << endl;
}

You should initialize your array like following:

cBruch cBruch[] = {{3, 4},{24, -6},{-5, -3},{-14, 22},{21, 45},{7, -9},{2, 3}};

The comma operator will always evaluate both sides and return the right hand side. It also has the lowest precedence of all opearators.

So, this:

cBruch[2] = -5, -3;

evaluates to:

(cBruch[2] = -5), -3;

And this:

cBruch[0] = (3, 4);

Will evaluate to:

cBruch[0] = 4;

You probably should use an array (or better yet a std::array ) of for example std::pair<int, int> .

Apparently I can't read... You need {} rather than (). – HolyBlackCat

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM