How to get integer quotient when divide two values in c#?

Viewed 37546

I want get integer quotient when I divide two values. Per example

X=3
Y=2
Q=X/Y = 1.5 // I want get 1 from results


X=7
Y=2
Q=X/Y=3.5 //I want get only 3 from results
6 Answers

try using simple maths

int X = 10 ;
int Y = 3 ; 
int Q = ( X - ( X % Y ) ) / Y  ; // ( it will give you the correct answer ) 

It works by subtracting the remainder beforehand from the first number so that we don't get a remainder at all !

There is another elegant way of getting quotient and remainder in .NET using Math.DivRem() method which takes 2 input parameter, 1 output parameter and returns integer.

using System;

For dividend: 7 and divisor: 2

To get only quotient(q)

int q = Math.DivRem(7, 2, _);
//requires C# >= 7.0 to use Discards( _ )

To get quotient(q) and remainder(r)

int q = Math.DivRem(7, 2, out int r);

Math.DivRem() has 2 overloads for 32-bit and 64-bit signed integers.

Related