Home > Back-end >  how to enforce the evaluation type of an expression to be double
how to enforce the evaluation type of an expression to be double

Time:06-15

how could I make sure that the expression is always evaluated as a double even if it has no double in it, I came across this website https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types, It says :

check the relevant part from here so how can I override this problem and make sure that the expression is always evaluated as a double,

I am trying to use the library of Flee, and whenever I put a fraction in it like(4/3) it deals with it as an integer, not even a float, this ruins the whole calculation so I have to get around this problem,

If I try and use the following expression it works

(4.0/3) or (4/3.0) = 1.33333 the faulty case is as follows (4/3) = 1 hopefully my explanation is clear

CodePudding user response:

As mentioned in the docs, that is a feature of the language. You can always cast either the numerator or the denominator into a float or double which will end with a result of the same type:

int a = 4;
int b = 3;
double result = (double)a / b;

CodePudding user response:

Solution 1

Use the double annotation which tells to the compiler that the number is actually a double

4d / 3

(d for double, also works for float using f)

Solution 2

Use explicit casting

(double)4 / 3
  • Related