Develop a C program that defines a struct to represent a 3D vector and implement
ID: 3550331 • Letter: D
Question
Develop a C program that defines a struct to represent a 3D vector and implements four functions involving 3D vectors. Use the following program as a starting point. The function main provides code to test the 4 functions. You are to provide code to implement the functions.
#include <stdio.h>
#include <math.h>
typedef struct
{
float x;
float y;
float z;
} vector;
vector getVector(void);
void printVector(vector v);
vector addVectors(vector* v1, vector* v2);
float magnitude(vector* v);
int main()
{
vector v1, v2, v3;
printf(" Enter vector v1: ");
v1 = getVector();
printf(" v1 = ");
printVector(v1);
printf(" |v1| = %0.2f", magnitude(&v1));
printf(" Enter vector v2: ");
v2 = getVector();
printf(" v2 = ");
printVector(v2);
printf(" |v2| = %0.2f", magnitude(&v2));
printf(" v1 + v2 = ");
v3 = addVectors(&v1, &v2);
printVector(v3);
return 0;
}
vector getVector(void)
{
}
void printVector(vector v)
{
}
vector addVectors(vector* v1, vector* v2)
{
}
float magnitude(vector* v)
{
}
Explanation / Answer
#include <stdio.h>
#include <math.h>
typedef struct
{
float x;
float y;
float z;
} vector;
vector getVector(void);
void printVector(vector v);
vector addVectors(vector* v1, vector* v2);
float magnitude(vector* v);
int main()
{
vector v1, v2, v3;
printf(" Enter vector v1: ");
v1 = getVector();
printf(" v1 = ");
printVector(v1);
printf(" |v1| = %0.2f", magnitude(&v1));
printf(" Enter vector v2: ");
v2 = getVector();
printf(" v2 = ");
printVector(v2);
printf(" |v2| = %0.2f", magnitude(&v2));
printf(" v1 + v2 = ");
v3 = addVectors(&v1, &v2);
printVector(v3);
return 0;
}
vector getVector(void)
{
vector temp;
printf("Enter vector using space(eg a i^ , b j^ , ck6 enter it as a b c):");
scanf("%f%f%f",&temp.x,&temp.y,&temp.z);
return temp;
}
void printVector(vector v)
{
printf("%0.2f i , %0.2f j , %0.2f k ",v.x,v.y,v.z);
}
vector addVectors(vector* v1, vector* v2)
{
vector temp;
temp.x= v1->x + v2->x;
temp.y= v1->y + v2->y;
temp.z= v1->z + v2->z;
return temp;
}
float magnitude(vector* v)
{
return sqrt((v->x * v->x)+(v->y * v->y)+(v->z * v->z));
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.