RPlay
RPlay

Reputation: 361

How to define a constant by expression in C++?

I need some like this:

const float ratio = 1/60;

How to do this?

Upvotes: 5

Views: 438

Answers (4)

juanchopanza
juanchopanza

Reputation: 227390

If you need a ratio, as opposed to the result of one, you can use std::ratio:

constexpr one_sixtieth = std::ratio<1, 60>();

constexpr auto n = one_sixtieth.num;
constexpr auto d = one_sixtieth.den;

It comes with a set of useful compile time operations.

Upvotes: 5

kfsone
kfsone

Reputation: 24249

Exactly as you have done but tell the compiler the values in the expression are floats with a "f" suffix

const float ratio = 1.0f/60.0f;

Upvotes: 9

Vishal R
Vishal R

Reputation: 1074

You try this

const float numerator =1;
const float denominator =60;
const float ratio = numerator/denominator;

Upvotes: 0

mvp
mvp

Reputation: 116117

You don't really need constexpr, this will work in C or C++:

const float ratio = 1./60;

Upvotes: 7

Related Questions