Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.7 kB
13
Indexable
Never
#include<stdio.h>

typedef struct {
    double i, j, k;
} Vector;


void print (Vector *v){
    printf("(%.2lf, %.2lf, %.2lf)\n", v->i, v->j, v->k);
}

/// add
/// sub
/// scalar mul
/// dot
/// cross
/// scalar division

/**
void add (Vector *v1, Vector *v2, Vector *v3){
    v3->i = v1->i + v2->i;
    v3->j = v1->j + v2->j;
    v3->k = v1->k + v2->k;
}
*/

Vector * add (Vector *v1, Vector *v2) {
    Vector *v3=(Vector *) malloc(sizeof(Vector));
    v3->i = v1->i + v2->i;
    v3->j = v1->j + v2->j;
    v3->k = v1->k + v2->k;
    return v3;
}

Vector* sub (Vector *v1, Vector *v2) {
    Vector *v3 = (Vector*) malloc(sizeof(Vector));

    v3->i = v1->i - v2->i;
    v3->j = v1->j - v2->j;
    v3->k = v1->k - v2->k;
    return v3;
}

void scalarMul (Vector *v, int c) {
    v->i *= c;
    v->j *= c;
    v->k *= c;
}

double dot (Vector *v1, Vector *v2) {
    return v1->i * v2->i + v1->j * v2->j + v1->k * v2->k;
}

Vector * cross (Vector *v1, Vector *v2) {
    Vector *v3 = (Vector *) malloc(sizeof(Vector));

    v3->i = v1->j * v2->k - v1->k * v2->j;
    v3->j = v1->k * v2->i - v1->i * v2->k;
    v3->k = v1->i * v2->j - v1->j * v2->i;

    return v3;
}

void scalarDiv(Vector *v, double d) {
    v->i /= d;
    v->j /= d;
    v->k /= d;
}

int main()
{
    Vector v1= {5, 7, 9};
    Vector v2= {1,2, 3};

    Vector *v3 = add(&v1, &v2);
    print(v3);
    v3 = sub(&v1, &v2);
    print(v3);
    scalarMul(v3, 3);
    print(v3);
    printf("%0.2lf\n", dot(&v1, &v2));
    v3 = cross(&v1, &v2);
    print(v3);
    scalarDiv(v3, 5);
    print(v3);
    free(v3);

    return 0;
}
Leave a Comment