1

What would be the best variable type for storing GPS coordinates in a C++ program? I wrote the code below just to try it out and regardless of what variable types I chose the problem persisted.

#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;

class Coordinate {
    public:
            float xcoor, ycoor;
            int radius;
            void set_values (float, float, int);

};

void Coordinate::set_values (float x, float y, int r){
    xcoor = x;
    ycoor = y;
    radius = r;
}

int main (){
    Coordinate test;
    test.set_values (32.682633, -117.181554, 50);
    cout << "coordinates: (" << test.xcoor << "," << test.ycoor << ")\n";
    return 0;
}

This code outputs the values: (32.6826,-117.182)

So obviously I am losing huge amounts of precision, but is there anyway I could maintain it? I haven't done GPS coordinates before and couldn't find anyone with a similar problem. Thank you for your help.

DNA
  • 42,007
  • 12
  • 107
  • 146
whla
  • 739
  • 1
  • 12
  • 26

2 Answers2

2

using floating point variables in arithmetic can lead in a loss of precision, but as far as I see you do not do any calculation with your coordinates.

I suspect that you are assuming that std::cout does output floating point variables with full precision, which is not the case by default.

double test = 1.23456789;
std::cout.precision(10);
std::cout << "test: " << test << std::endl; // prints "test: 1.23456789"

See that question, as well as the documentation of ostreams for further information.

Community
  • 1
  • 1
Theolodis
  • 4,977
  • 3
  • 34
  • 53
1

As far as I can see it only prints 6 digits. Try either setw or setprecision. With the former you can set a constant with to print out numbers or characters (this comes handy at aligning), the latter sets how many digits your program prints.

With floats you shouldn't lose any data from those numbers.

JanosP
  • 21
  • 3