Assertion failure with remquo function

62 Views Asked by At

The piece of code I am working on has the aim to create a spreadsheet of 104 columns and lines. Columns header as you can guess increments the alphabet. After the Z letter, you have the AA through AZ and so on.

For now I testing the fact that after the Z the code loops from A through Z until it fills the 104 columns headers.

Here is the code:

#include "spreadhall.h"
#include <cmath>

SpreadWnd::SpreadWnd()
{
    formulaInput = new QLineEdit;

    table = new QTableWidget;
    table->setRowCount(104); // int row = table->rowCount();
    table->setColumnCount(104); int col = table->columnCount();
    table->setSizeAdjustPolicy(QTableWidget::AdjustToContents);

    QString s[26] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
                     "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    QString str = "";
    for(int i = 0; i < col; i++)
    {
        //int r = (i + 1) % 26;
        if(i > 25)
        {
            int q;
            int r = remquo(i, 25, &q);
            if(r == 0) r = 25;
            str = s[r - 1];
        }
        else
            str = s[i];
        table->setHorizontalHeaderItem(i, new QTableWidgetItem(str));
    }

    vLay = new QVBoxLayout;
    vLay->addWidget(formulaInput);
    vLay->addWidget(table);

    this->setLayout(vLay);
}

The For loop is the piece of code that writes the headers. When I use the code in comment at the first line in the For loop, everything works fine, the headers loop back from A to Z. But when I use the remquo function, I get an assertion failure at runtime. I don't understand why.

Is someone has any idea of what is wrong?

N.B:

I am not using the remainder function because I will need the quotient to design the AA after the Z and so on.

I am using Qt5.3 with MSVC2013 on a 64 bits Acer laptop on Win8 platform.

Thanks!

1

There are 1 best solutions below

1
On BEST ANSWER

The problem you are facing is a consequence of the way remquo() calculates the remainder. If you have a look to the docs you see that:

The IEEE floating-point remainder of the division operation x/y calculated by this function is exactly the value x - n*y, where the value n is the integral value nearest the exact value x/y

Hence, for certain values, the quotient is rounded up to the next integer, resulting in a negative value for the remainder, i.e. a negative index for your s array.

Consider for instance remquo(13, 25, x). You got that:

13 / 25 = 0.52

The quotient is rounded up to 1 and you got a resulting remainder of:

13 - 1 * 25 = -12

You can use div instead of remquo(), which returns the expected values:

div_t d = div(13, 25);
qDebug() << d.quot;    // x / y  --> 0
qDebug() << d.rem;     // x % y  --> 13