Search code examples
carraysinversion

Inverse a coefficient of a table


I have a file with 256 coefficient and I want to inverse each 64 coefficient of this file and keep the result in another file. I try to program my idea but the result is wrong.

int main()
{     
    /***********************************inversion coefficients*****************/
    FILE* org = NULL; // original file
    FILE* inv = NULL; // file content inverse coefficient
    float det; // readed coefficient 
    float tabinv[256]; // intermediate table witch will content iverse coefficient
    org = fopen("det.txt", "r");
    inv = fopen("inverse.txt", "w");
    int j = 64;
    int p = j;
    int copt = 0;
    while (copt < 256)
    {
        for (int i = j - 64; i < j; i++)
        {

            fscanf(org, "%f", &det);

            tabinv[p - 1 - i] = det;

            copt++;

        }

        p = p + 64;

        j = p;
    }
    for (int k = 0; k < 256; k++){
        fprintf(inv, "%f\n", tabinv[k]);

    }
    fclose(org);
    fclose(inv);
    return 0;
}

Solution

  • You have Fix in this line-

     tabinv[p - 1 - i] = det; // Don't use same variable i.
    

    Normally From the expression int i = j - 64,when p=j=64, i=0, that time it stores the value from tabinv[63] to tabinv[0]. But when p=j=128, i=64, that time also it start stores the value from tabinv[63] to tabinv[0]. You need to fix this to avoid the error.

    Try the following change-

    for (int i = j - 64,int k = 0; i < j; i++,k++) // Fix 1
    {
    
        fscanf(org, "%f", &det);
    
        tabinv[p - 1 - k] = det; // Fix 2
    
        copt++;
    
    }