Simple C++ question

Started by
5 comments, last by scottrick49 14 years, 10 months ago
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 :)
__________________________________________
Eugene Alfonso
GTP | Twitter | SFML | OS-Dev
Advertisement
Array indices start at zero, not 1.

change:

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


to:

dist3(coords1[0], coords1[1], coords1[2], coords2[0], coords2[1], coords2[2]);


I think that's your problem.
scottrick49
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)
__________________________________________
Eugene Alfonso
GTP | Twitter | SFML | OS-Dev
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);
scottrick49
Ah yeah. Thanks again.
__________________________________________
Eugene Alfonso
GTP | Twitter | SFML | OS-Dev
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 );
lol yeah i wasn't actually thinking about what the function was supposed to do...
scottrick49

This topic is closed to new replies.

Advertisement