user3064203
user3064203

Reputation: 101

int and double operations in C++

I am trying to convert latitude and longitude locations from degrees, minutes, seconds to a decimal degree number. However, when I try to do this in C++ it rounds the numbers off and doesn't give the decimal form. I think this is because of the double and int mixed operations but I can't seem to find the problem. I have included my code below. Any help would be greatly appreciated.

#include <iomanip>
#include <cmath>
#include <iostream>
#include <string>
using namespace std;

int main()
{
int user_degrees_latitude, user_minutes_latitude, user_seconds_latitude, user_degrees_longitude, user_minutes_longitude, user_seconds_longitude;
double total_minutes_latitude, total_degrees_latitude, total_minutes_longitude, total_degrees_longitude;
const double sixtieth = (1/60);

cout<< "Input latitude in degrees, minutes, seconds:";
cin >> user_degrees_latitude >> user_minutes_latitude >> user_seconds_latitude;

cout << "Input longitude in degrees, minutes, seconds:";
cin >> user_degrees_longitude >> user_minutes_longitude >> user_seconds_longitude;

total_minutes_latitude = (user_minutes_latitude + (((sixtieth)*user_seconds_latitude));
total_degrees_latitude = (abs(user_degrees_latitude) + ((sixtieth)*total_minutes_latitude));

total_minutes_longitude = (user_minutes_longitude + ((sixtieth)*user_seconds_longitude));
total_degrees_longitude = (abs(user_degrees_longitude) + ((sixtieth)*total_minutes_longitude));

cout << user_degrees_latitude << " deg " << user_minutes_latitude << "\' " << user_seconds_latitude << "\" latitude, " << user_degrees_longitude << " deg " << user_minutes_longitude << "\' " << user_seconds_longitude << "\"";
cout << " is (" << total_degrees_latitude << "," << total_degrees_longitude << ")"<<endl;





    return 0;
}

Upvotes: 1

Views: 3644

Answers (3)

user3116431
user3116431

Reputation: 283

Could also do the job:

const double sixtieth = (double)1/60;

Or preferred in C++

const double sixtieth = static_cast<double>(1)/60;

const double sixtieth = 1.0/60; Is preferred here though as your are working with rvalues.

You would need double or static_cast in case of lvalues:

int numerator = 1;
int denominator = 60;


const double sixtieth = (double) numerator/denominator;
const double sixtieth = static_cast<double>(numerator)/denominator;

Upvotes: 1

Steve Jessop
Steve Jessop

Reputation: 279395

I haven't looked through all the code, but this is wrong:

const double sixtieth = (1/60);

1/60 is 0, always. This is not a mixed operation, it is integer only. You should write:

const double sixtieth = (1.0/60);

Upvotes: 4

user2357112
user2357112

Reputation: 281958

1/60 is integer division, which rounds toward zero. That means your sixtieth variable is 0. You may be doing integer division in other places, too. If you want your division to be floating-point, make sure at least one argument is floating-point.

Upvotes: 6

Related Questions