January 29, 2016 To cast a uint to float to compute k/n, use to! or cast()? | ||||
---|---|---|---|---|
| ||||
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? |
January 29, 2016 Re: To cast a uint to float to compute k/n, use to! or cast()? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Enjoys Math | 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
|
Copyright © 1999-2021 by the D Language Foundation