#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 << ")";
}
Simple C++ question
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?
Thanks :)
Array indices start at zero, not 1.
change:
to:
I think that's your problem.
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.
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)
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)
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:
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);
Quote:Original post by scottrick49float 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 );
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement