Asif
Asif

Reputation: 184

How to check the number is among the sets of numbers in C#

I have a condition like:

if X is between (1 to 4) ----- value 0
if X is between(4 to 8) ----- value 1
if X is between(8 to 12) ----- value 2
if X is between(12 to 16) ----- value 3

and so on....

What is the best way to do this in C#?

Upvotes: 0

Views: 126

Answers (4)

Richard Schwartz
Richard Schwartz

Reputation: 14628

Integer division in C# truncates, so if the number you are talking about is an integer and is assigned to the variable myInt, all you have to do is write an expression like this:

(myInt -1) / 4.

And if the number is a float, casting to int truncates, so just cast it like this:

((int) myFloat - 1) /4

Upvotes: 1

shanish
shanish

Reputation: 1984

You can simply do it like

int result = (X - 1) / 4;

Upvotes: 0

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try like this

int x=5;
int num = (int)Math.Ceiling(x/4.0)-1;
Console.WriteLine(num);

Upvotes: 1

alexm
alexm

Reputation: 6882

simply divide by 4:

int c = (int)(x - 1) / 4;

Upvotes: 4

Related Questions