What does -Convert.ToSingle do? - c#

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

Related

Why is my result not displaying decimals? C# [duplicate]

Does anyone know why integer division in C# returns an integer and not a float?
What is the idea behind it? (Is it only a legacy of C/C++?)
In C#:
float x = 13 / 4;
//== operator is overridden here to use epsilon compare
if (x == 3.0)
print 'Hello world';
Result of this code would be:
'Hello world'
Strictly speaking, there is no such thing as integer division (division by definition is an operation which produces a rational number, integers are a very small subset of which.)
While it is common for new programmer to make this mistake of performing integer division when they actually meant to use floating point division, in actual practice integer division is a very common operation. If you are assuming that people rarely use it, and that every time you do division you'll always need to remember to cast to floating points, you are mistaken.
First off, integer division is quite a bit faster, so if you only need a whole number result, one would want to use the more efficient algorithm.
Secondly, there are a number of algorithms that use integer division, and if the result of division was always a floating point number you would be forced to round the result every time. One example off of the top of my head is changing the base of a number. Calculating each digit involves the integer division of a number along with the remainder, rather than the floating point division of the number.
Because of these (and other related) reasons, integer division results in an integer. If you want to get the floating point division of two integers you'll just need to remember to cast one to a double/float/decimal.
See C# specification. There are three types of division operators
Integer division
Floating-point division
Decimal division
In your case we have Integer division, with following rules applied:
The division rounds the result towards zero, and the absolute value of
the result is the largest possible integer that is less than the
absolute value of the quotient of the two operands. The result is zero
or positive when the two operands have the same sign and zero or
negative when the two operands have opposite signs.
I think the reason why C# use this type of division for integers (some languages return floating result) is hardware - integers division is faster and simpler.
Each data type is capable of overloading each operator. If both the numerator and the denominator are integers, the integer type will perform the division operation and it will return an integer type. If you want floating point division, you must cast one or more of the number to floating point types before dividing them. For instance:
int x = 13;
int y = 4;
float x = (float)y / (float)z;
or, if you are using literals:
float x = 13f / 4f;
Keep in mind, floating points are not precise. If you care about precision, use something like the decimal type, instead.
Since you don't use any suffix, the literals 13 and 4 are interpreted as integer:
Manual:
If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.
Thus, since you declare 13 as integer, integer division will be performed:
Manual:
For an operation of the form x / y, binary operator overload resolution is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator.
The predefined division operators are listed below. The operators all compute the quotient of x and y.
Integer division:
int operator /(int x, int y);
uint operator /(uint x, uint y);
long operator /(long x, long y);
ulong operator /(ulong x, ulong y);
And so rounding down occurs:
The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.
If you do the following:
int x = 13f / 4f;
You'll receive a compiler error, since a floating-point division (the / operator of 13f) results in a float, which cannot be cast to int implicitly.
If you want the division to be a floating-point division, you'll have to make the result a float:
float x = 13 / 4;
Notice that you'll still divide integers, which will implicitly be cast to float: the result will be 3.0. To explicitly declare the operands as float, using the f suffix (13f, 4f).
Might be useful:
double a = 5.0/2.0;
Console.WriteLine (a); // 2.5
double b = 5/2;
Console.WriteLine (b); // 2
int c = 5/2;
Console.WriteLine (c); // 2
double d = 5f/2f;
Console.WriteLine (d); // 2.5
It's just a basic operation.
Remember when you learned to divide. In the beginning we solved 9/6 = 1 with remainder 3.
9 / 6 == 1 //true
9 % 6 == 3 // true
The /-operator in combination with the %-operator are used to retrieve those values.
The result will always be of type that has the greater range of the numerator and the denominator. The exceptions are byte and short, which produce int (Int32).
var a = (byte)5 / (byte)2; // 2 (Int32)
var b = (short)5 / (byte)2; // 2 (Int32)
var c = 5 / 2; // 2 (Int32)
var d = 5 / 2U; // 2 (UInt32)
var e = 5L / 2U; // 2 (Int64)
var f = 5L / 2UL; // 2 (UInt64)
var g = 5F / 2UL; // 2.5 (Single/float)
var h = 5F / 2D; // 2.5 (Double)
var i = 5.0 / 2F; // 2.5 (Double)
var j = 5M / 2; // 2.5 (Decimal)
var k = 5M / 2F; // Not allowed
There is no implicit conversion between floating-point types and the decimal type, so division between them is not allowed. You have to explicitly cast and decide which one you want (Decimal has more precision and a smaller range compared to floating-point types).
As a little trick to know what you are obtaining you can use var, so the compiler will tell you the type to expect:
int a = 1;
int b = 2;
var result = a/b;
your compiler will tell you that result would be of type int here.

Why is C# casting double to int?

I have a function in which I need to pass a double. To call that function, I am using the following code:-
static int Main()
{
double d = 1/7 ;
Console.WriteLine("The value of d is {0}", d) ;
calc(d) ;
return 0 ;
}
The output of the following program is
The value of d is 0
Why is this so, why is C# truncating the part ahead of decimal, despite storing 1/7 in a double?
An int divided by an int uses integer truncation.
Use:
static int Main()
{
double d = 1.0 / 7 ;
//^^ or d = 1.0 / 7.0
Console.WriteLine("The value of d is {0}", d) ;
calc(d) ;
return 0 ;
}
Promoting either numerator or denominator (or both) to a floating point type promotes the result of the division to a floating point type.
Refs:
Division operator
/ Operator
Because what you doing is here called integer division. It always discards the fractional part. That's why 1 / 7 always give you 0 as a result regardless which type you assign it.
.NET has 3 type of division. From 7.7.2 Division operator
Integer division
Floating-point division
Decimal division
Also from / Operator (C# Reference)
When you divide two integers, the result is always an integer. For
example, the result of 7 / 3 is 2. To obtain a quotient as a rational
number or fraction, give the dividend or divisor type float or type
double.
So, as a result, you can use one of these if you want fractional part;
double d = 1.0 / 7 ;
double d = 1 / 7.0 ;
double d = 1.0 / 7.0 ;
According to C# reference
For an operation of the form x / y, binary operator overload
resolution (Section 7.2.4) is applied to select a specific operator
implementation. The operands are converted to the parameter types of
the selected operator, and the type of the result is the return type
of the operator.
This means that the operator / selects the correct overloads looking at its parameters. In your case your parameters are integer so, the operator selects the integer division that returns an integer (truncating the remainder)
To avoid this and select the floating point division you should give an hint forcing one of your constants to be a double/float
double d = 1.0 / 7 ;
Because the first parameter in 1/7 is an integer, so c# does a integer-division.
You'll get the correct result if you type:
double d = (double)1/7;
What you have here is operation precedence.
In effect you have written
int temp = 1 / 7;
double d = temp;
Which actually gets compiled to
int temp = 0;
double d = temp;
or
double d = 0;
The reason being is that you are using the int divide operator
static operator int / (int, int)
when you meant to use the
static operator double /(double, double)
You can force that by writing
double d = 1.0 / 7;
OR
double d = 1d / 7d;
etc etc
C# is statically-typed at compile time. Your code (double d = 1/7;) is run in the following manner in the run time.
var temp = 1/7;
double d = temp;
Here, 1 and 7 are integers. So, the division operation returns only integer and stored it in the temporary location. After that, the variable d is created and the temporary value is stored in that variable. So, here the implicit type conversion will not work.
So, you have to done the explicit type conversion at the time of division. 1.0/7 or 1/7.0 or (double)1/7 or 1/(double)7 will return the double value. So, the integer to double implicit cast will not apply here and you will get your desired result.
If you specify your number as 1 without decimal point, an int type is assumed. Replace the line
double d = 1/7 ;
with
double d = 1.0/7 ;
Alternatively you can specify the type as double using suffix:
double d = 1d/7 ;
In C# and Java (and most programming languages) the type of the result is the type of the of the numerator and denominator. You have to cast the integers that make up the numerator and denominator into doubles if you want the result to be a double.
Try double d = 1d/7d or double d = (double)(1/7)

Learning C#, Math equation not resulting as expected

Learning C#, Math equation not resulting as expected.
This is apart of my homework. I do not understand why the result are not coming out as them should..
First equation
m=2
n=1
int sideA = (m^2) - (n^2);
result -3
Second equation
x1=2
x2=7
float Xmid = (x1 + x2)/2;
result 4
This is because in C# ^ means XOR, not "raised to the power of". To square a number, use
Math.Pow(x, 2)
or simply
x * x
Also dividing integers truncates the fractional part. Use decimal, double, or float to get 3.5 as the midpoint of 3 and 4:
float x1=2
float x2=7
float Xmid = (x1 + x2)/2;
Your first line of code:
int sideA = (m^2) - (n^2);
Is basically m XOR 2 minus n XOR 2. XOR is a bitwise operator that results in the bits where one is true but not both. For more information on the exclusive OR operator, consult Wikipedia. If you're trying to raise m to the power of 2, try something like:
int sideA = Math.Pow(m, 2) - Math.Pow(n, 2);
Your second line of code:
float Xmid = (x1 + x2)/2;
Is (2 + 7) which is 9, divided by the integer 2 which is 4.5, however because dividing an integer by another integer will always result in an integer, only the integer portion of the result will be kept. The fact that you're assigning this expression to a float is irrelevant.
You might want to try:
float Xmid = (x1 + x2)/2.0;
or:
float Xmid = (x1 + x2)/2f;
or declare x1 and x2 as floats, both which will yield 4.5.

Why does integer division in C# return an integer and not a float?

Does anyone know why integer division in C# returns an integer and not a float?
What is the idea behind it? (Is it only a legacy of C/C++?)
In C#:
float x = 13 / 4;
//== operator is overridden here to use epsilon compare
if (x == 3.0)
print 'Hello world';
Result of this code would be:
'Hello world'
Strictly speaking, there is no such thing as integer division (division by definition is an operation which produces a rational number, integers are a very small subset of which.)
While it is common for new programmer to make this mistake of performing integer division when they actually meant to use floating point division, in actual practice integer division is a very common operation. If you are assuming that people rarely use it, and that every time you do division you'll always need to remember to cast to floating points, you are mistaken.
First off, integer division is quite a bit faster, so if you only need a whole number result, one would want to use the more efficient algorithm.
Secondly, there are a number of algorithms that use integer division, and if the result of division was always a floating point number you would be forced to round the result every time. One example off of the top of my head is changing the base of a number. Calculating each digit involves the integer division of a number along with the remainder, rather than the floating point division of the number.
Because of these (and other related) reasons, integer division results in an integer. If you want to get the floating point division of two integers you'll just need to remember to cast one to a double/float/decimal.
See C# specification. There are three types of division operators
Integer division
Floating-point division
Decimal division
In your case we have Integer division, with following rules applied:
The division rounds the result towards zero, and the absolute value of
the result is the largest possible integer that is less than the
absolute value of the quotient of the two operands. The result is zero
or positive when the two operands have the same sign and zero or
negative when the two operands have opposite signs.
I think the reason why C# use this type of division for integers (some languages return floating result) is hardware - integers division is faster and simpler.
Each data type is capable of overloading each operator. If both the numerator and the denominator are integers, the integer type will perform the division operation and it will return an integer type. If you want floating point division, you must cast one or more of the number to floating point types before dividing them. For instance:
int x = 13;
int y = 4;
float x = (float)y / (float)z;
or, if you are using literals:
float x = 13f / 4f;
Keep in mind, floating points are not precise. If you care about precision, use something like the decimal type, instead.
Since you don't use any suffix, the literals 13 and 4 are interpreted as integer:
Manual:
If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.
Thus, since you declare 13 as integer, integer division will be performed:
Manual:
For an operation of the form x / y, binary operator overload resolution is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator.
The predefined division operators are listed below. The operators all compute the quotient of x and y.
Integer division:
int operator /(int x, int y);
uint operator /(uint x, uint y);
long operator /(long x, long y);
ulong operator /(ulong x, ulong y);
And so rounding down occurs:
The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.
If you do the following:
int x = 13f / 4f;
You'll receive a compiler error, since a floating-point division (the / operator of 13f) results in a float, which cannot be cast to int implicitly.
If you want the division to be a floating-point division, you'll have to make the result a float:
float x = 13 / 4;
Notice that you'll still divide integers, which will implicitly be cast to float: the result will be 3.0. To explicitly declare the operands as float, using the f suffix (13f, 4f).
Might be useful:
double a = 5.0/2.0;
Console.WriteLine (a); // 2.5
double b = 5/2;
Console.WriteLine (b); // 2
int c = 5/2;
Console.WriteLine (c); // 2
double d = 5f/2f;
Console.WriteLine (d); // 2.5
It's just a basic operation.
Remember when you learned to divide. In the beginning we solved 9/6 = 1 with remainder 3.
9 / 6 == 1 //true
9 % 6 == 3 // true
The /-operator in combination with the %-operator are used to retrieve those values.
The result will always be of type that has the greater range of the numerator and the denominator. The exceptions are byte and short, which produce int (Int32).
var a = (byte)5 / (byte)2; // 2 (Int32)
var b = (short)5 / (byte)2; // 2 (Int32)
var c = 5 / 2; // 2 (Int32)
var d = 5 / 2U; // 2 (UInt32)
var e = 5L / 2U; // 2 (Int64)
var f = 5L / 2UL; // 2 (UInt64)
var g = 5F / 2UL; // 2.5 (Single/float)
var h = 5F / 2D; // 2.5 (Double)
var i = 5.0 / 2F; // 2.5 (Double)
var j = 5M / 2; // 2.5 (Decimal)
var k = 5M / 2F; // Not allowed
There is no implicit conversion between floating-point types and the decimal type, so division between them is not allowed. You have to explicitly cast and decide which one you want (Decimal has more precision and a smaller range compared to floating-point types).
As a little trick to know what you are obtaining you can use var, so the compiler will tell you the type to expect:
int a = 1;
int b = 2;
var result = a/b;
your compiler will tell you that result would be of type int here.

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;

Categories