简体   繁体   中英

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;
}

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.

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);

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM