What does the /= operator in C# do? - c#

What does the /= operator in C# do and when is it used?

It's divide-and-assign. x /= n is logically equivalent to x = x / n.

It is similar to +=, -= or *=. It's a shortcut for a mathematical division operation with an assignment. Instead of doing
x = x / 10;
You can get the same result by doing
x /= 10;
It assigns the result to the original variable after the operation has taken place.

In most languages inspired by C, the answer is: divide and assign. That is:
a /= b;
is a short-hand for:
a = a / b;
The LHS (a in my example) is evaluated once. This matters when the LHS is complex, such as an element from an array of structures:
x[i].pqr /= 3;

a /= 2; is the same of a = a / 2;.

A division and an assignment:
a /= b;
is the same as
a = (a / b);
Its simply a combination of the two operators into one.

In the following example:
double value = 10;
value /= 2;
Value will have a final value of 5.
The =/ operator divides the variable by the operand (in this case, 2) and stores the result back in the variable.

a /= b;
is the same as
a = a / b;
Here's the msdn article on the operator.

Related

Algorithm to round two numbers to the nearest evenly divisible ones

The title is not really well phrased, I'm aware - can't think of a better way of writing it though.
Here's the scenario - I have two input boxes, both representing integer quantities. One is represented in our units, the other in the vendor's units. There is a multiplier defining how to convert from ours to theirs. In the below example, I'm saying that two of our units is equal to five of theirs. So, for example,
decimal multiplier = 0.4; // Two of our units equals five of theirs
int requestedQuantity = 11; // Our units
int suppliedQuantity = 37; // Their units
// Should return 12, since that is the next highest whole number that results in both of us having whole numbers (12 of ours = 30 of theirs)
int correctedFromRequestedQuantity = GetCorrectedRequestedQuantity(requestedQuantity, null, multiplier);
// Should return 16, since that is the next highest whole number that results in both of us having whole numbers (16 of ours = 40 of theirs);
int correctedFromSuppliedQuantity = GetCorrectedRequestedQuantity(suppliedQuantity, multiplier, null);
Here's the function I've written to handle this. I'm not doing a divide by zero check on the multiplier / rounder since I've already checked for that elsewhere. It seems crazy to do all that converting, but is there a better way of doing it?
public int GetCorrectedRequestedQuantity(int? input, decimal? multiplier, decimal? rounder)
{
if (multiplier == null)
{
if (rounder == null)
return input.GetValueOrDefault();
else
return (int)Math.Ceiling((decimal)((decimal)Math.Ceiling(input.GetValueOrDefault() / rounder.Value) * rounder.Value));
}
else if (input.HasValue)
{
// This is insane...
return (int)Math.Ceiling((decimal)((decimal)Math.Ceiling((int)Math.Ceiling((decimal)input * multiplier.Value) / multiplier.Value) * multiplier.Value));
}
else
return 0;
}
Represent the multiplier as a fraction in lowest terms. I don't know if .NET has a fractions class but if not you can probably find a C# implementation, or just write your own. So assume the multiplier is given by two integers a / b in lowest terms, with a ≠ 0 and b ≠ 0. That also means that conversion in the other direction is given by multiplying by b / a. In your example, a = 2 and b = 5, and a / b = 0.4.
Now suppose you want to convert an integer X. If you think about it a bit you'll see what you really want is to nudge X up until b divides X. The number you need to add to X is simply (b - (X%b)) % b. So to convert on one direction is just
return (a * (X + (b - (X % b) % b))) / b;
and to convert Y going in the other direction is just
return (b * (Y + (a - (X % a) % a))) / a;
My best idea of my head is to semi brute-force it. It does sound like it is basically Fraction Mathematics. So there might be a way easier solution for this.
First we need to find in what sort of "Batch" the multiplier becomes whole. That way, we can stop working with floats/doubles altogether. Ideally this should be supplied with the multiplier (as float math is messy).
double currentMultiple=multiplier;
int currentCount=0;
//This is the best check for "is an integer" could think off.
while(currentMultiple % 1 = 0){
//The Framework can detect Arithmetic Overflow. Let us turn that one on
//If we ever get there, likely the math is non-solveable
checked{
currentMultiple+= multiplier;
currentCount += 1;
}
}
//You get here either via exception or because you got a multiple that solves it.
//Store the value of currentCount into a variable "OurBatchSize"
//Also store the value of currentMultiple in "TheirBatchSize"
Getting the closest Multiple of OurBatchSize:
int requestedQuantity = 11; // Our units
int result = OurBatchSize;
int batchCount = 0;
while(temp < requestedQuantity){
result += OurBatchSize;
batchCount++
}
//result contains the answer here. Return it
//batchCount * TheirBatchSize will also tell you how much they get.
Edit: Credit for this goes mostly to James Reinstate Monica Polk. He had the math idea to use Modulo for this. Here is what I got with explanation:
int result;
int rest = requestedAmout % BatchSize;
if (rest != 0){
//Correct upwards to the next multiple
int DistanceToNextMultiple = BatchSize - Rest;
result = requestedAmout + DistanceToMultiple;
}
else{
//It already is right
result = requestedAmout;
}
For the BatchSize of 4, you will get:
13; 13%4=1; 4-1=3; 13+3=16;
14; 14%4=2; 4-2=2; 14+2=16;
15; 15%4=3; 4-3=1; 15+1=16;
16; 16%4=0; Else is used. 16 is already right.

Why result of % operator for double differ from decimal? [duplicate]

Consider this:
double x,y;
x =120.0;
y = 0.05;
double z= x % y;
I tried this and expected the result to be 0, but it came out 0.04933333.
However,
x =120.0;
y = 0.5;
double z= x % y;
did indeed gave the correct result of 0.
What is happening here?
I tried Math.IEEERemainder(double, double) but it's not returning 0 either. What is going on here?
Also, as an aside, what is the most appropriate way to find remainder in C#?
Because of its storage format, doubles cannot store every values exactly as is is entered or displayed. The human representation of numbers is usually in decimal format, while doubles are based on the dual system.
In a double, 120 is stored precisely because it's an integer value. But 0.05 is not. The double is approximated to the closest number to 0.05 it can represent. 0.5 is a power of 2 (1/2), so it can be stored precisely and you don't get a rounding error.
To have all numbers exactly the same way you enter / display it in the decimal system, use decimal instead.
decimal x, y;
x = 120.0M;
y = 0.05M;
decimal z = x % y; // z is 0
You could do something like:
double a, b, r;
a = 120;
b = .05;
r = a - Math.floor(a / b) * b;
This should help ;)
I believe if you tried the same with decimal it would work properly.
http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems can help you understand why you get these "strange" results. There's a particular precision that floating point numbers can have. Just try these queries and have a look at the results:
0.5 in base 2
0.05 in base 2
Modulus should only be used with integer. The remainder come from an euclidean division. With double, you can have unexpected results.
See this article
This is what we use.. :)
public double ModuloOf(double v1, double v2)
{
var mult = 0;
//find number of decimals
while (v2 % 1 > 0)
{
mult++;
v2 = v2 * 10;
}
v1 = v1 * Math.Pow(10, mult);
var rem = v1 % v2;
return rem / Math.Pow(10, mult);
}

What does -Convert.ToSingle do?

I tried to search on Google and Bing this but both return zero results....
What does it mean when you put a hyphen in front of convert?
-Convert.ToSingle
It's just the - operator, applied to the result of calling Convert.ToSingle(...).
So for example when used as a unary operator:
double x = 10.52123;
float y = -Convert.ToSingle(x);
is equivalent to:
double x = 10.52123;
float tmp = Convert.ToSingle(x);
float y = -tmp;
Or when used as a binary operator:
double x = 10.52123;
float y = 10-Convert.ToSingle(x);
is equivalent to:
double x = 10.52123;
float tmp = Convert.ToSingle(x);
float y = 10 - tmp;
I'd say it's shorthand for
-1 * Convert.ToSingle(...)
Since the method returns a Single (which is a number, so it's subject to arithmetic operators)
The - operator is an unary or a binary operator. The result of a unary - operation on a numeric type is the numeric negation of the operand. For an example
int x = 5;
float b = -Convert.ToSingle(x);
Console.WriteLine(b);
Here the output should be -5. In the absence of unary operator. The output value should have been just 5
Just think about the C# syntax: what means a minus at the right of an assignment? In every language (or almost, don't talk to me about Brainfuck & co), it means change the sign of the number which following.
So the operation after this minus has to return a Number. Good, that's what Convert.ToSingle does, which returns a float.
float x = - Convert.ToSingle(42);
^ ^^^^^^^^^^^^^^^^
^ function call
minus operation
// equivalent to:
float x = 0 - Convert.ToSingle(42);
^^^
0 minus the result

modulus operator in C#

Which function we can use to find modulus of floating point value ?
Theres probably a function somewhere but the following is equivalent and simple enough:
a - b*(Math.Floor(a/b))
for a % b
math.h in old C has the function fmod. would c# even allow you to to use it? i dont know either way.
PS - are you sure the % operator doesnt work?
Float/double are never exact values, therefore % operator will not work consistently. Use decimal instead to make modulus operator work on real numbers.
decimal a, b c;
a = 32.3M;
b = 3.23M;
c = a % b; //c should be zero.
EDIT
Check Avoid modulus operator with types float and double section (Bottom of the page) on MSDN.
Is there a problem with using the standard modulo operator % ?
double c = a%b;
float x = 5.1F;
float y = 2.3F;
float t = x % y;

Simple division [duplicate]

This question already has answers here:
Why returns C# Convert.ToDouble(5/100) 0.0 and not 0.05
(7 answers)
Closed 9 years ago.
I must be doing something dumb:
float ans = (i/3);
So why when i = 7 is ans coming out at 2.0?
i is an int
It's because the / operator is performing an integer division if both operands are integers. You could do this:
float ans = (i / 3.0f);
You need to make one of the operands a float, otherwise the calculation is done with integers first (which always results in an integer), before converting the result to a float.
float ans = ((float) i) / 3;
It's doing integer division because i is an int and 3 is an int. Try this:
float ans = ((float)i/3.0f);
use float ans = (i / 3.0) or float ans = (i / 3f) or float ans = ((float)i / 3). / does an integer division if both sides are of type integer.
Very simple: in C#, int / int = int.
What you're looking for is:
float ans = ((float)i/3);
Otherwise you're taking two integers and dividing them to find the number of whole times the divisor goes in to the dividend. (As mentioned, an int/int=int regardless of the destination type. And, to the compiler, "3" is another integer (unless you specify it as 3.0f))
I am assuming that you have this in a loop of some sort. You could specify your i variable as a float instead.
for (float i = 0; i < 10; i++)
{
float ans = (i/3);
// statements
}
Just another solution.

Categories