Declare float or cast float?
I've started to learn C++ using "C++ Primer by Stephen Prate" and I'm currently trying to complete one of the exercises. I am wondering if I should declare arc_to_minute & arc_to_degree as float or cast them as float as I've done already. Any tips welcome!
#include <iostream>开发者_开发技巧;
int main()
{
using namespace std;
cout.setf(ios_base::fixed, ios_base::floatfield);
const int arc_to_minute = 60;
const int arc_to_degree = 60;
float degrees;
float minutes;
int seconds;
cout << "Degrees: ";
cin >> degrees;
cout << "Minutes: ";
cin >> minutes;
cout << "Seconds: ";
cin >> seconds;
//convert seconds to minutes and add
minutes = minutes + seconds / float (arc_to_minute);
//covert minutes to degrees and add
degrees = degrees + minutes / float (arc_to_degree);
cout << degrees;
}
Make them floats, there's no reason for them to be integers when all your calculations are done in floating point:
const float arc_to_minute = 60.0f;
const float arc_to_degree = 60.0f;
Keep in mind in a constant-value case the cast will be done at compile-time anyway, so this is purely a design choice, with no performance changes. But in general, if you find yourself casting, you probably chose the incorrect data type to begin with.
For what it's worth, you should prefer C++ style casts when you do need to cast. For example:
static_cast<float>(arc_to_minute);
Declare them as float (or better yet, double) because that's how you're going to use them.
I do not see a problem either way. Happy learning!
Edit: But for casting, prefer static_cast.
精彩评论