c# - How can I define mathematical constants without typing out the number? -
i need use square root of two, 1.414..., in loop.
obviously, don't want call function math.sqrt(2) time. sure, it's single instruction on modern processors, , jit or compiler figure out what's going on, want code clear, readable, , fast.
because want code clear , readable, i'd prefer define constant calling sqrt2 = math.sqrt(2)
instead of typing in magic number sqrt2 = 1.4142135623731d
.
finally, because value constant, want declare const
keyword. when write:
const double sqrt2 = math.sqrt(2); // const double sqrt2 = 1.4142135623731d;
the compiler complains:
error 1 expression being assigned 'sqrt2' must constant
how best define value?
math.sqrt
method call, cannot assigned compile-time constant.
can assign run-time constant:
static readonly double sqrt2 = math.sqrt(2);
Comments
Post a Comment