R
R
Ruslan2020-10-10 09:08:55
Qt
Ruslan, 2020-10-10 09:08:55

Why don't values ​​change in a c++ loop?

Look, I made a table and I'm trying to fill it with different elements, so far I want to fill the first column with numbers using For, but it turns out like this:
5f814fc173478769614024.png
why does this happen? I assume that the created itm element does not change?

void MainWindow::on_pushButton_clicked()
{
    //Тут создаем таблицу с 20 полями и с 2 заголовками
   // Тут создаем переменные вьюшек
    QString al = ui->a->text();
    QString xnl = ui->xn->text();
    QString xhl = ui->xh->text();
    QString xkl = ui->xk->text();
    



   //Тут переменные сишарповские
    double a = al.toDouble();
    double xn = xnl.toDouble();
    double xh = xhl.toDouble();
    double xk = xkl.toDouble();
    double x;
    double y;
    int counter = 0;
    //
    for(int i = 0; i<ui->tableWidget->rowCount();i++)
        for(x = xn;x<=xk;x = x+xh)
        {

            if (x <= -1) {
                        y = (sqrt(pow(x,2) + a)) - pow(a,2);

                    }
                    else
                    {
                    if(x == -2){
                        y = pow(cos(pow(x,3)), 2) - x / sqrt(pow(a,2)+1);
                    }
                    else{
                        if((x>-1) && (x<=-2.9)){
                            y = pow(sin(x+a),3) / x;

                        }
                    }
                    }
            QTableWidgetItem *itm = new QTableWidgetItem(QString::number(y));
            ui->tableWidget->setItem(i,0,itm);
            x = x+xh;
        }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Grigory, 2020-10-10
@ruprup

Apparently, the idea was to fill the table with results for different X. But in fact, each time you calculate a new Y, you add them to the same table cell and you have all the cells calculated at the maximum X.
In short, you need to calculate in advance the number of required cells in table, do
ui->tableWidget->setRowCount(newSize);(or something like that)
and bring your loop to the form:

int i = 0;
for(x = xn;x<=xk;x = x+xh, ++i) {
// Расчет очередного Y
  QTableWidgetItem *itm = new QTableWidgetItem(QString::number(y));
  ui->tableWidget->setItem(i,0,itm);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question