views:

142

answers:

3

Hey

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

I do not see a problem either way. Happy learning!

Edit: But for casting, prefer static_cast.

Amit Kumar
+3  A: 

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);
GMan
In this case, the cast might be done at compile time, since there are no operations that use the int flavor and it's a local variable. This is not in general true, however. When casting from an int to a double on any chip I know about, the compiler has to issue instructions to copy from an int register to a floating point register, which will perform the conversion.
Joel
I meant in this case, updated to clarify.
GMan
+2  A: 

Declare them as float (or better yet, double) because that's how you're going to use them.

Mark Ransom
Yes, double operations are quite fast on modern processors, and sometimes faster than the float operations. I think I am right.
Amit Kumar
I was always under the impression that floats were promoted to doubles before any arithmetic was performed, anyway.
Mark Ransom
According to the language standard, either promoting them or not promoting them is acceptable.
dan04