Значение int64_t переполняется в структуре в C - PullRequest
0 голосов
/ 12 мая 2018

Я хочу создать многочлен с одним термином: 6/5 и отобразить его. Следует напечатать это: 6 / 5X ^ 0

Структура полинома:

typedef struct __poly_struct_t *poly_t;
struct __poly_struct_t{
    unsigned int deg;
    ratio_t *coeffs;
};

Где ratio_t - массив рациональных чисел, его структура:

typedef struct __ratio_struct_t{
    int64_t num;
    int64_t den;
}ratio_t;

Я использовал две функции для построения этого полинома. PolyFromRatioArray работает: он печатает 6 / 5X ^ 0

poly_t polyFromRatioArray(ratio_t *c, unsigned int degree){
    poly_t p = (struct __poly_struct_t*)malloc(sizeof(struct __poly_struct_t));
    p->deg = degree;
    p->coeffs = c;
    return p;
}

Другой перепутал знаменатель: отпечатки polyFromRatio 6 / 140218959144480X ^ 0

poly_t polyFromRatio(ratio_t c){
    return polyFromRatioArray(&c, 0);
}

Основная функция:

int main(){
    ratio_t ra = createRatio((int64_t)6,(int64_t)5);
    poly_t p1 = polyFromRatioArray(&ra, 0);  // one that works
    polyPrint(p1);
    poly_t p2 = polyFromRatio(ra);  // this doesn't
    polyPrint(p2);
    free(p1);
    free(p2);
    return 0;
}

Другие задействованные функции:

ratio_t createRatio(int64_t a, int64_t b){
    if(b == 0){
        printf("Error : a divise by 0 \n");
        exit(1);
    }
    ratio_t r;
    int64_t pgcd = gcd(a, b); // gcd(int64_t a, int64_t b) is a function that finds pgcd using Euclid.
    r.num = a/pgcd;
    r.den = b/pgcd;
    return r;
}

int64_t gcd(int64_t a, int64_t b){
    int64_t u, v, g;
    ext_eucl_div(&u, &v, &g, llabs(a), llabs(b));
    return g;
}

void ext_eucl_div(int64_t *u, int64_t *v, int64_t *g, int64_t a, int64_t b){ // this function stocks pgcd of a and b in g
    int64_t u1, u2, u3 , v1, v2, v3, q, t1, t2, t3;
    int tour = 0;
    do{
        if(tour == 0){
             u1 = 1; u2 = 0; u3 = a; v1 = 0; v2 = 1; v3 = b;
        }
        else{
            u1 = v1; u2 = v2; u3 = v3; v1 = t1; v2 = t2; v3 = t3;
        }
        q = u3/v3;
        t1 = u1 - q*v1;
        t2 = u2 - q*v2;
        t3 = u3%v3;
        tour++;
    } while(t3>=1);
    *u = v1;
    *v = v2;
    *g = v3;
}

void polyPrint(poly_t p){
    unsigned int i;
    for(i=0; i<= p->deg; i++){
        if(p->coeffs[i].num != 0){
            printRatio(p->coeffs[i]);
            if(i != p->deg) printf("X^%u + ", i);
            else printf("X^%u\n", i);
        }else printf("0\n");
    }
}

void printRatio(ratio_t a){
    printf("%" PRId64, a.num);
    printf("/%" PRId64, a.den);
}

Это очень странно, кажется, что polyFromRatioArray и polyFromRatio делают одно и то же, но нет.

...