Sign in to follow this  
phear-

Simple C++ question

Recommended Posts

I'm starting to get back into programming again and im in the process of rereading some of my books to get my memory working again and im having trouble with some basic stuff that I just can't remember. The exercise was to make a function that calculates the distance between 2 3D coords. The error im getting is that my arrays are uninitialized. I thought that using an initializer {} would work. Any thoughts?
#include <iostream>
#include <cmath>
#include <string>

using namespace std;

float dist3(float ux, float uy, float uz, float vx, float vy, float vz);
void print3(float x, float y, float z);

int main()
{
	float coords1[3] = {1.0f, 2.0f, 3.0f};
	float coords2[3] = {0.0f, 0.0f, 0.0f};
	float coords3[3] = {7.0f, -4.0f, 5.0f};

	dist3(coords1[1], coords1[2], coords1[3], coords2[1], coords2[2], coords2[3]);
	dist3(coords1[1], coords1[2], coords1[3], coords1[1], coords1[2], coords1[3]);
	dist3(coords1[1], coords1[2], coords1[3], coords3[1], coords3[2], coords3[3]);

	system("pause");
}

float dist3(float ux, float uy, float uz, float vx, float vy, float vz)
{
	float x = vx - ux;
	float y = vy - uy;
	float z = vz - uz;
	float total = sqrtf(x+y+z);
	cout << "Distance between ";
	print3(ux, uy, uz);
	cout << " and ";
	print3(vx, vy, vz);
	cout << " = " << total << endl;
	return total;
}

void print3(float x, float y, float z)
{
	cout << "(" << x << ", " << y << ", " << z << ")";
}

Thanks :)

Share this post


Link to post
Share on other sites
That fixed it, thanks. I forgot about that, haha.
Any ideas why the first solution looks wierd when outputted in the console?
The other 2 solutions look fine (0 and 1.41...) but the 1st solution is (-1.#IND)

Share this post


Link to post
Share on other sites
probably because you are taking the square root of a negative number?

edit: this will actually work - take the absolute value of each of the items before you add them together:


float x = abs(vx - ux);
float y = abs(vy - uy);
float z = abs(vz - uz);
float total = sqrtf(x+y+z);

Share this post


Link to post
Share on other sites
Quote:
Original post by scottrick49

float x = abs(vx - ux);
float y = abs(vy - uy);
float z = abs(vz - uz);
float total = sqrtf(x+y+z);


Whoops, not quite.

It should be:

float x = vx - ux;
float y = vy - uy;
float z = vz - uz;
float total = sqrtf( x*x + y*y + z*z );

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this