Precedence of cast in c# [duplicate] - c#

This question already has answers here:
Cast operation precedence in C#
(3 answers)
Closed 8 years ago.
What is the precedence of a cast in c#? For example in the following code, will z be less than or equal to two?
double x = 4.5;
double y = 2.1;
double z = (int) x / y;

The cast beats all binary operators for binding. Hence (int)x / y means ((int)x)/y.
On the other hand, you should always prefer readable code to clever code, so since you don't know you should write the following instead:
((int)x) / y
Note that brackets are free, and make your code more readable.

Less than:
using System;
public class Test
{
public static void Main()
{
double x = 4.5;
double y = 2.1;
double z = (int) x / y;
Console.WriteLine(z);
}
}
See here: http://ideone.com/fhg5ai

z will be less than two:
double x = 4.5;
double y = 2.1;
double z = (int) x / y;
Console.WriteLine(z); //1.9047619047619
Your code is really doing this: ((int)x) / y, which may or may not be your expected output.

Related

Why is x 1 when assigning a double?

I'm very new with C#.
I don't understand why is x = 1 and not 1.4.
Can please somebody explain me this?
double x = (double)(12 / 5 - 3 % 2);
Console.WriteLine(x);
Because this is NOT about double.
You are integer-executing
(12 / 5 - 3 % 2);
and THEN casting to double. If you want this to be about double, then make sure at least one of the numbers is a double. In your case just mark the literals as double.
(12d / 5d - 3d % 2d);
is all doubles. As long as one is a double, the operation happens as double - but your original case makes all the calculations, THEN casts to double. So they happen as integer.
You're doing integer math and then converting to double. 12 / 5 = 2, 3 % 2 = 1, and 2 - 1 = 1.
Welcome to stackoverflow! :)
The problem is that you are operating all int, and afterwards converting them to double.
You need to make sure that you are operating with doubles from the beginning.
Try out the code in here: https://dotnetfiddle.net/xaQjKL
using System;
public class Program
{
public static void Main()
{
// Doubles from the beggining
double d_twelve = 12.0;
double d_five = 5.0;
double x = (double)(d_twelve / d_five);
Console.WriteLine($"Using all doubles: {x}");
// First split two int, then convert the result to double
int i_twelve = 12;
int i_five = 5;
x = (double)(i_twelve / i_five);
Console.WriteLine($"Using ints, and converting at the end to double: {x}");
// And now your code:
x = (double)(12 / 5 - 3 % 2);
Console.WriteLine($"Your original code: {x}");
// And now your code fixed (notice the 12 => 12.0):
x = (double)(12.0 / 5 - 3 % 2);
Console.WriteLine($"Changing 12 by 12.0: {x}");
}
}
You are doing operations with integers and then casting he result to a double.
double x = (12d / 5d - 3d % 2d);
Console.WriteLine(x);
Adding d after a number will make it a double while adding f will make it a float.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types#real-literals
Because you use integer values inside the parenthesis, and the expression is calculated using integer math before being cast to double.
You can use a double value for the first value and it should be enough:
> double x = (12d / 5) - (3 % 2);
> Console.WriteLine(x);
1.4

I wrote the code right? [duplicate]

This question already has answers here:
Find Cube root of a number Using System.Math.Pow() method in C#
(5 answers)
Closed 6 years ago.
According to the equation above this, I wrote here such code:
Double x = 16.55 * Math.Pow(10.0, -3);
Double y = -2.75;
Double z = 0.15;
Double kvadrat_koren_3 = Math.Pow(x, 1/3);
Double vozvedenie_v_stepen = Math.Pow(x, y + 2);
Double Summa_v_Skobkax = kvadrat_koren_3 + vozvedenie_v_stepen;
Double Kvadrat_koren_10 = Math.Sqrt(10.0 * Summa_v_Skobkax);
Double ArcSinus = Math.Pow(Math.Asin(z), 2) - Math.Abs(x - y);
Double Beta = Kvadrat_koren_10 * ArcSinus;
Console.WriteLine(Math.Round(Beta, 5));
But the calculation of the result issued: -41.31532, as needed: -40.63069.
Where am I wrong to write the expression?
P.S. I am using the latest version of SharpDevelop, and teach himself programming to change jobs.
Your problem is with the following: Math.Pow(x, 1/3); you're using integers for 1/3, which will give you an integer result of 0, rather than 0.33333etc.
Change the expression to Math.Pow(x, 1.0/3.0);

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);
}

Adding delegate in C# [duplicate]

This question already has answers here:
Events and Delegates in F#
(3 answers)
Closed 9 years ago.
How does one add a new function to a delegate without using the += notation ?
I wonder how to do his from another CLR langage, namely F#. (I know there are much nicer way to deal with events in F#, but I am being curious..)
static int Square (int x) { return x * x; }
static int Cube(int x) { return x * x * x; }
delegate int Transformer (int x);
Transformer d = Square ;
d += Cube;
Edit
As pointed out by Daniel in the comments, the fact that one has no direct way of doing this probably is a design decision by dotnet team to not mutate the queue too much.
Here is one way to do it in F#. You need downcasting due to the use of Delegate.Combine:
let square x = x * x
let cube x = x * x * x
type Transformer = delegate of int -> int
let inline (++) (a: 'T) (b: 'T) =
System.Delegate.Combine(a, b) :?> 'T
let d = Transformer(square)
let e = d ++ Transformer(cube)
Delegate.Combine?
d = (Transformer) Delegate.Combine(d, new Transformer(Cube));

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