Home > Coding > 3D vector distance calculation

3D vector distance calculation

Recently I decided to revisit Vectors. Being something that while I covered in A-Level Physics,  but never really grasped beyond the basics.

So in the process of messing around with vectors, I wrote a small 3D vector distance calculator in PHP, which I then proceeded to port to C++ for fun. Code is below, and I’ll release the EXE if someone wants it, not really useful unless you want a quick(ish) way of getting distances I suppose.

Enjoy:

< ?php
 function distance($a, $b)
 {
  return sqrt(pow($a[0] - $b[0], 2) + pow($a[1] - $b[1], 2) + pow($a[2] - $b[2], 2));
 }

 $a = array(-1, 0, 6);
 $b = array(5, 2, 10);
 
 echo distance($a, $b); 
?>
#include <iostream>
#include <math .h>

using namespace std;

float distance(float &Bx, float &By, float &Bz)
{
 float Ax = 0.0f, Ay = 0.0f, Az = 0.0f;
 return sqrt(pow(Ax - Bx, 2) + pow(Ay - By, 2) + pow(Az - Bz, 2)); 
}

int main()
{
 float x, y, z;
 bool loop;

 do
 {
  cout < < "Enter vector:" << endl << "X: ";
  cin >> x;
  cout < < "Y: ";
  cin >> y;
  cout < < "Z: ";
  cin >> z;

  cout < < "Result: " << distance(x, y, z) << endl << "Again? 1/0: ";
  cin >> loop;
 } while(loop == true); 

 return 0;
}

Download: EXE ~10 KiB

Categories: Coding Tags: ,
  1. No comments yet.
  1. No trackbacks yet.
Easy AdSense by Unreal