www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - To cast a uint to float to compute k/n, use to! or cast()?

reply Enjoys Math <enjoysmath gmail.com> writes:
I want to compute the points of a regular polygon in a loop:

float r = 1.0;

for (uint k=0; k < numVerts; k++) {
    vertlist ~= Vec2D(r * cos(k/n * 2 * PI), ...)
}

How do I make sure k/n is a float or double?
Jan 29 2016
parent Steven Schveighoffer <schveiguy yahoo.com> writes:
On 1/29/16 6:48 PM, Enjoys Math wrote:
 I want to compute the points of a regular polygon in a loop:

 float r = 1.0;

 for (uint k=0; k < numVerts; k++) {
     vertlist ~= Vec2D(r * cos(k/n * 2 * PI), ...)
 }

 How do I make sure k/n is a float or double?
uint is promoted to float/double with a binary math operation. You could simply reverse the order of your expression: 2 * PI * k/n But if you want to force a type change with simple conversions such as these, just use a constructor: float(k) / n * 2 * PI There is no need to cast or use `to` (though both of those would be equivalent to simple conversion). -Steve
Jan 29 2016