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
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 !
Related
This simple calculation is returning zero, I can't figure it out:
decimal share = (18 / 58) * 100;
You are working with integers here. Try using decimals for all the numbers in your calculation.
decimal share = (18m / 58m) * 100m;
18 / 58 is an integer division, which results in 0.
If you want decimal division, you need to use decimal literals:
decimal share = (18m / 58m) * 100m;
Since some people are linking to this from pretty much any thread where the calculation result is a 0, I am adding this as a solution as not all the other answers apply to case scenarios.
The concept of needing to do calculations on various types in order to obtain that type as a result applies, however above only shows 'decimal' and uses it's short form such as 18m as one of the variables to be calculated.
// declare and define initial variables.
int x = 0;
int y = 100;
// set the value of 'x'
x = 44;
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0. The conversion to double happens
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );
// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
Because the numbers are integers and you perform integer division.
18 / 58 is 0 in integer division.
Whenever I encounter such situations, I just upcast the numerator.
double x = 12.0 / 23409;
decimal y = 12m / 24309;
Console.WriteLine($"x = {x} y = {y}");
double res= (firstIntVar * 100f / secondIntVar) / 100f;
when dividing numbers I use double or decimal , else I am getting 0 , with this code even if firstIntVar && secondIntVar are int it will return the expected answer
decimal share = (18 * 100)/58;
Solved: working perfectly with me
int a = 375;
int b = 699;
decimal ab = (decimal)a / b * 100;
I have a number ("double") from int/int (such as 10/3).
What's the best way to Approximation by Excess and convert it to int on C#?
Are you asking about System.Math.Ceiling?
Math.Ceiling(0.2) == 1
Math.Ceiling(0.8) == 1
Math.Ceiling(2.6) == 3
Math.Ceiling(-1.4) == -1
int scaled = (int)Math.Ceiling( (double) 10 / 3 ) ;
By "Approximation by Excess", I assume you're trying to "round up" the number of type double. So, #Doug McClean's "ceiling" method works just fine.
Here is a note:
If you start with double x = 0.8; and you do the type conversion by (int)x; you get 0. Or, if you do (int)Math.Round(x); you get 1.
If you start with double y = 0.4; and you do the type conversion by (int)y; you get 0. Or, if you do (int)Math.Round(y); you get 0.
Consider 2.42 , you can say it's 242/100 btw you can simplify it to 121/50 .
This simple calculation is returning zero, I can't figure it out:
decimal share = (18 / 58) * 100;
You are working with integers here. Try using decimals for all the numbers in your calculation.
decimal share = (18m / 58m) * 100m;
18 / 58 is an integer division, which results in 0.
If you want decimal division, you need to use decimal literals:
decimal share = (18m / 58m) * 100m;
Since some people are linking to this from pretty much any thread where the calculation result is a 0, I am adding this as a solution as not all the other answers apply to case scenarios.
The concept of needing to do calculations on various types in order to obtain that type as a result applies, however above only shows 'decimal' and uses it's short form such as 18m as one of the variables to be calculated.
// declare and define initial variables.
int x = 0;
int y = 100;
// set the value of 'x'
x = 44;
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0. The conversion to double happens
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );
// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
Because the numbers are integers and you perform integer division.
18 / 58 is 0 in integer division.
Whenever I encounter such situations, I just upcast the numerator.
double x = 12.0 / 23409;
decimal y = 12m / 24309;
Console.WriteLine($"x = {x} y = {y}");
double res= (firstIntVar * 100f / secondIntVar) / 100f;
when dividing numbers I use double or decimal , else I am getting 0 , with this code even if firstIntVar && secondIntVar are int it will return the expected answer
decimal share = (18 * 100)/58;
Solved: working perfectly with me
int a = 375;
int b = 699;
decimal ab = (decimal)a / b * 100;
I need to find a division of two integers and round it to next upper integer
e.g x=7/y=5 = 2; here x and y always greater than 0
This is my current code
int roundValue = x % y > 0? x / y + 1: x / y;
Is there any better way to do this?
You could use Math.Ceiling... but that will require converting to/from double values.
Another alternative is to use Math.DivRem to do both parts at the same time.
public static int DivideRoundingUp(int x, int y)
{
// TODO: Define behaviour for negative numbers
int remainder;
int quotient = Math.DivRem(x, y, out remainder);
return remainder == 0 ? quotient : quotient + 1;
}
Try (int)Math.Ceiling(((double)x) / y)
All solutions looks too hard. For upper value of x/y, use this one
( x + y - 1 ) / y
dunno what's better way or how to define a better way (if in terms of performance you have to run tests to see which will be faster), but here's my solution:
int roundValue = x / y + Convert.ToInt32(x%y>0);
p.s.
still have to deal somehow with neg. numbers... IMO this is the simplest.
+0.5 will aways round to the higher.
Use ceil() function.
It gives the upper value.
It's better to use MidpointRounding from Math.Round
In your case:
Math.Round(value, MidpointRounding.AwayFromZero);
see more: https://learn.microsoft.com/ru-ru/dotnet/api/system.math.round?view=net-6.0#system-math-round(system-double-system-midpointrounding)
I am coding a program where a form opens for a certain period of time before closing. I am giving the users to specify the time in seconds. But i'd like this to be in mutliples of five. Or the number gets rounded off to the nearest multiple.
if they enter 1 - 4, then the value is automatically set to 5.
If they enter 6 - 10 then the value is automatically set to 10.
max value is 60, min is 0.
what i have, but i am not happy with this logic since it resets it to 10 seconds.
if (Convert.ToInt32(maskedTextBox1.Text) >= 60 || Convert.ToInt32(maskedTextBox1.Text) <= 0)
mySettings.ToastFormTimer = 10000;
else
mySettings.ToastFormTimer = Convert.ToInt32 (maskedTextBox1.Text) * 1000;
use the Modulus Operator
if(num % 5 == 0)
{
// the number is a multiple of 5.
}
what about this:
int x = int.Parse(maskedTextBox1.Text)/5;
int y = Math.Min(Math.Max(x,1),12)*5; // between [5,60]
// use y as the answer you need
5 * ((num - 1) / 5 + 1)
Should work if c# does integer division.
For the higher goal of rounding to the upper multiple of 5, you don't need to test whether a number is a multiple. Generally speaking, you can round-up or round-to-nearest by adding a constant, then rounding down. To round up, the constant is one less than n. Rounding an integer down to a multiple of n is simple: divide by n and multiply the result by n. Here's a case where rounding error works in your favor.
int ceil_n(int x, int n) {
return ((x+n-1) / n) * n;
}
In dynamic languages that cast the result of integer division to prevent rounding error (which doesn't include C#), you'd need to cast the quotient back to an integer.
Dividing by n can be viewed as a right-shift by 1 place in base n; similarly, multiplying by n is equivalent to a left-shift by 1. This is why the above approach works: it sets the least-significant digit of the number in base n to 0.
2410=445, 2510=505, 2610=515
((445+4 = 535) >>5 1) <<5 1 = 505 = 2510
((505+4 = 545) >>5 1) <<5 1 = 505 = 2510
((515+4 = 605) >>5 1) <<5 1 = 605 = 3010
Another way of zeroing the LSD is to subtract the remainder to set the least significant base n digit to 0, as Jeras does in his comment.
int ceil_n(int x, int n) {
x += n-1;
return x - x%n;
}