double value = 0;
value = 2 - (10 / 20);
return value ; // return 2
and testign with d
double value = 0;
value = 2 - (10 / 20d);
return value ; // return 1.5
How should I work with doubles? have to add “d” next to a value with a possible decimal result??? How this exactly works? I dont want to check AAAAALLLL my code and testing each operation!
Yes, working with doubles is the same as working with floats, you need to be careful with how you write the numbers in your operations.
The fact is that in your first version:
double value = 0;
value = 2 - (10 / 20);
return value ; // return 2
You have a double variable however your entire operation, ( 2 - ( 10 / 20)) is working only with integers, since you aren’t specifying a “f” for float or a “d” for double. 10 / 20 is an integer division not a float, nor a double division, and from an integer point of view, 20 cannot divide 10, there’s no way you can fit a 20 inside a 10, so you get 0 as a result. 2 - 0 = 2 so you get a 2 that is an integer and then C#, with enormous kindness and understanding, automatically casts your result int into a double so it can be stored inside your variable of type double, instead of throwing an type error.
In your second version when you add the “d”:
double value = 0;
value = 2 - (10 / 20d);
return value ; // return 1.5
You are making the 20 be represented as a double, that means that C# will cast the 10 to a double so it can perform the division. The result of the division will now be a double (which is 0.5 since you can only fit half of a 20 inside a 10) and that means that the result of the subtraction will also be turned into a double.
So, to sum up and answer your question:
Do I have to add “d” next to a value with a possible decimal result???
The answer is yes. You have to get into the hobby of adding a “d” (or an “f” if you want to use floats instead) when you are dealing with numbers that you expect to have decimal places.