65 lines
1.4 KiB
C
65 lines
1.4 KiB
C
/* Angle Between Two Vectors
|
||
*
|
||
* A prgorgam that calculates the angle between to vectors
|
||
* givien 𝑎 and 𝑏 of each vector.
|
||
*/
|
||
#include <stdio.h>
|
||
#include <stdlib.h>
|
||
#include <math.h>
|
||
|
||
int main() {
|
||
float a1, b1, a2, b2; /* Vector Compenents */
|
||
|
||
/* Print the vector forms */
|
||
printf("Vector form: 𝑎𝐢 + 𝑏𝐣 or <𝑎, 𝑏>\n");
|
||
|
||
/* Prompt user for variables */
|
||
printf("Enter 𝑎₁: ");
|
||
scanf("%f", &a1);
|
||
|
||
printf("Enter 𝑏₁: ");
|
||
scanf("%f", &b1);
|
||
|
||
printf("Enter 𝑎₂: ");
|
||
scanf("%f", &a2);
|
||
|
||
printf("Enter 𝑏₂: ");
|
||
scanf("%f", &b2);
|
||
|
||
/* Sanity Check
|
||
*
|
||
* If 𝑎 and 𝑏 equal 0, exit the program.
|
||
*/
|
||
if ((a1 == 0 && b1 == 0) || (a2 == 0 && b2 == 0)) {
|
||
printf("Error: Division by 0\n");
|
||
|
||
exit(1);
|
||
};
|
||
|
||
/* Calculate values of additional variables */
|
||
float cosr = (a1 * a2 + b1 * b2) / (sqrt(a1 * a1 + b1 * b1) * sqrt(a2 * a2 + b2 * b2));
|
||
float r = acos(cosr); /* Angle in radians */
|
||
float d = r * (180 / M_PI); /* Angle in degrees */
|
||
|
||
/* Sanity Check
|
||
*
|
||
* Sometimes the caulculations are not percise enough.
|
||
*
|
||
* If variable cosr is greater than or equal to 1 or
|
||
* less than or equal to -1, r = 0 or pi, and d = 0 or 180.
|
||
*/
|
||
if (cosr > 1) {
|
||
r = d = 0;
|
||
} else if (cosr < -1) {
|
||
r = M_PI;
|
||
d = 180;
|
||
}
|
||
|
||
/* Print angle between the two vectors */
|
||
printf("Angle in radians: %.2f\n", r);
|
||
printf("Angle in degrees: %.2f\n", d);
|
||
|
||
return 0;
|
||
}
|
||
|
||
|