开发者

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

I w开发者_StackOverflow中文版ant 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


Integer math is going to do this for you.

int x = 3 / 2; // x will be 1
int y = 7 / 2; // y will be 3
int z = 7 % 2; // z will be 1

If you were using decimal or floating-point values in your equations, that would be different. The simplest answer is to cast the result to an int, but there are static Math functions you could also use.

double a = 11d;
double b = 2d;
int c = (int)(a / b); // showing explicit cast, c will be 5


Try Math.Truncate. This should do it.


In VB.NET there is the integer division operator (\). It returns only the integer portion of the division. This comes all the way from the original Dartmouth BASIC so it exists in most forms of BASIC.


try Math.Floor()


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.


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 !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜