S
Steven T. Hatton
I'm surprised I haven't hit this situation till now, but I don't believe
I've had to deal with it before. I have a function that sets the
components of a point class (QPoint from Qt). It takes integer arguments
for the components. I am calculating the values using transcendental
functions sin and cos which return floating point type values. (The
compiler claims they are double though I expected float in, float out.) I
guess I have some choices as to whether I pass the floating point values
and let the conversion take place automagically, or convert first and then
pass the resulting integers. How is such a situation typically handled in
C++?
So far as I know there is no explicit round() function native to C++ that
will round a float or double to an int or size_t. Is this correct?
Here's a code snippet that has the actual invocation in it:
namespace drawings
{
static float pi = acos(-1.0f); // not sure if static is right here.
StarFactory::StarFactory():
edgeLength(100.0f)
{
size_t n = StarFactory::NUMBER_OF_POINTS;
this->pointArrayPtr = new QPointArray(n);
float dTheta = 2.0f/float(n) * pi;
float l = this->edgeLength;
for(size_t i = 0; i < n; i++)
{
float theta = float(i) * dTheta;
/*The following line is where the conversion happens*/
this->pointArrayPtr->setPoint(i, l * cos(theta), l * sin(theta));
}
}
StarFactory::~StarFactory()
{
/// @todo destroy me
}
}
;
I've had to deal with it before. I have a function that sets the
components of a point class (QPoint from Qt). It takes integer arguments
for the components. I am calculating the values using transcendental
functions sin and cos which return floating point type values. (The
compiler claims they are double though I expected float in, float out.) I
guess I have some choices as to whether I pass the floating point values
and let the conversion take place automagically, or convert first and then
pass the resulting integers. How is such a situation typically handled in
C++?
So far as I know there is no explicit round() function native to C++ that
will round a float or double to an int or size_t. Is this correct?
Here's a code snippet that has the actual invocation in it:
namespace drawings
{
static float pi = acos(-1.0f); // not sure if static is right here.
StarFactory::StarFactory():
edgeLength(100.0f)
{
size_t n = StarFactory::NUMBER_OF_POINTS;
this->pointArrayPtr = new QPointArray(n);
float dTheta = 2.0f/float(n) * pi;
float l = this->edgeLength;
for(size_t i = 0; i < n; i++)
{
float theta = float(i) * dTheta;
/*The following line is where the conversion happens*/
this->pointArrayPtr->setPoint(i, l * cos(theta), l * sin(theta));
}
}
StarFactory::~StarFactory()
{
/// @todo destroy me
}
}
;