I have this:
double result = 60 / 23;
In my program, the result is 2, but correct is 2,608695652173913. Where is problem?
60 and 23 are integer literals so you are doing integer division and then assigning to a double. The result of the integer division is 2.
Try
double result = 60.0 / 23.0;
Or equivalently
double result = 60d / 23d;
Where the d suffix informs the complier that you meant to write a double literal.
You can use any of the following all will give 2.60869565217391:
double result = 60 / 23d;
double result = 60d / 23;
double result = 60d/ 23d;
double result = 60.0 / 23.0;
But
double result = 60 / 23; //give 2
Explanation:
if any of the number is double it will give a double
EDIT:
Documentation
The evaluation of the expression is performed according to the following rules:
If one of the floating-point types is double, the expression evaluates to double (or bool in the case of relational or Boolean expressions).
If there is no double type in the expression, it evaluates to float (or bool in the case of relational or Boolean expressions).
It will work
double result = (double)60 / (double) 23;
Or equivalently
double result = (double)60 / 23;
(double) 60 / 23
Haven't used C# for a while, but you are dividing two integers, which as far as I remember makes the result an integer as well.
You can force your number literals to be doubles by adding the letter "d", likes this:
double result = 60d / 23d;
double result = 60.0 / 23.0;
It is best practice to correctly decorate numerals for their appropriate type. This avoids not only the bug you are experiencing, but makes the code more readable and maintainable.
double x = 100d;
single x = 100f;
decimal x = 100m;
convert the dividend and divisor into double values, so that result is double
double res= 60d/23d;
To add to what has been said so far... 60/23 is an operation on two constants. The compiler recognizes the result as a constant and pre-computes the answer. Since the operation is on two integers, the compiler uses an integer result The integer operation of 60/23 has a result of 2; so the compiler effective creates the following code:
double result = 2;
As has been pointed out already, you need to tell the compiler not to use integers, changing one or both of the operands to non-integer will get the compiler to use a floating-point constant.
Related
I wonder why my next statement always returns 1, and how I can fix it. I accounted for integer division by casting the first element in the division to float. Apart from that I'm not getting much further.
int value = any int;
float test = (float)value / int.MaxValue / 2 + 1;
By the way my intention is to make this convert ANY integer to a 0-1 float
To rescale a number in the range s..e to 0..1, you do (value-s)/(e-s).
So in this case:
double d = ((double)value - int.MinValue) / ((double)int.MaxValue - int.MinValue);
float test = (float)d;
It doesn't always return zero. For example, this code:
int value = 12345678;
float test = (float)value / int.MaxValue / 2 + 1;
Console.WriteLine(test);
Prints 1.002874
The problem is that floats are not very precise, so for small values of value, the result will be 0 to the number of digits of precision that floats can handle.
For example, value == 2300 will print 0, but value == 2400 will print 1.000001.
If you use double you get better results:
int value = 1;
double test = (double)value / int.MaxValue / 2 + 1;
Console.WriteLine(test);
Prints 1.00000000023283
Avoid implicit type conversions. Use all elements in your expression of type double, if that is the type you want. Convert the int.MaxValue and the 2 to double before using them in the division, so that no implicit type conversions are involved.
Also, you might want to parenthesize your expression to make it more readable. As it is, it is error prone.
Finally, if your expression is too complex and you don't know what's going on, split it into simpler expressions, all of them of type double.
P.S.: By the way, trying to get precise results and using float instead of double is not a very wise thing to do. Use float for precise floating point calculations.
I have the following code :
double a = 8/ 3;
Response.Write(a);
It returns the value 2. Why? I need at least one decimal digit. Something like 2.6, or 2.66. How can I get such results?
Try
double a = 8/3.0d;
or
double a = 8.0d/3;
to get a precise answer.
Since in expression a = 8/3 both the operands are int so the result is int irrespective of the fact that it is being stored in a double. The results are always in the higher data type of operands
EDIT
To answer
8 and 3 are get from variable. Can I do a sort of cast?
In case the values are coming from a variable you can cast one of the operands into double like:
int b = 8;
int c = 3;
double a = ((double) b) /c;
Because the calculation are being done in integer type not double. To make it double use:
double a = 8d/ 3d;
Response.Write(a);
Or
double a = 8.0/ 3.0;
Response.Write(a);
One of your operands should be explicitly marked as double either by using d or specifying a decimal point 0
or if you need you can cast them to double before the calculations. You can cast either one or both operands to double.
double a = ((double) 8)/((double)3)
because 8 and 3 are integer numbers and interpreter rounds it to 2.
You can simply advise to interpreter that you numbers are floating numbers:
double a = (double)8 / 3;
Because its making a rounding towards minus, its the way its implemented in the framework. However if you specify the precision by using the above example:
double a = 8/3.0d;
then rounding is no longer performed.
Or in simple terms you assigned an integer value to a double, thats why the rounding was performed in the first place. It saw an operation with integers.
Coz 8 and 3 both ints. And int's division operator with two ints in it returns int as well. (F12 when the cursor is on slash sign).
How do I divide an int by 100?
eg:
int x = 32894;
int y = 32894 / 100;
Why does this result in y being 328 and not 328.94?
When one integer is divided by another, the arithmetic is performed as integer arithmetic.
If you want it to be performed as float, double or decimal arithmetic, you need to cast one of the values appropriately. For example:
decimal y = ((decimal) x) / 100;
Note that I've changed the type of y as well - it doesn't make sense to perform decimal arithmetic but then store the result in an int. The int can't possibly store 328.94.
You only need to force one of the values to the right type, as then the other will be promoted to the same type - there's no operator defined for dividing a decimal by an integer, for example. If you're performing arithmetic using several values, you might want to force all of them to the desired type just for clarity - it would be unfortunate for one operation to be performed using integer arithmetic, and another using double arithmetic, when you'd expected both to be in double.
If you're using literals, you can just use a suffix to indicate the type instead:
decimal a = x / 100m; // Use decimal arithmetic due to the "m"
double b = x / 100.0; // Use double arithmetic due to the ".0"
double c = x / 100d; // Use double arithmetic due to the "d"
double d = x / 100f; // Use float arithmetic due to the "f"
As for whether you should be using decimal, double or float, that depends on what you're trying to do. Read my articles on decimal floating point and binary floating point. Usually double is appropriate if you're dealing with "natural" quantities such as height and weight, where any value will really be an approximation; decimal is appropriate with artificial quantities such as money, which are typically represented exactly as decimal values to start with.
328.94 is not an integer. Integer / divide rounds down; that is how it works.
I suggest you cast to decimal:
decimal y = 32894M / 100;
or with variables:
decimal y = (decimal)x / 100;
Because an int is only a whole number. Try this instead.
int x = 32894;
double y = x / 100.0;
Because you're doing integer division. Add a period behind the 100 and you'll get a double instead.
When you divide two integers, the result is an integer. Integers don't have decimal places, so they're just truncated.
its programming fundamental that int(integer) dividing is different from float(floating point) dividing.
if u want .94 use float or double
var num = 3294F/100F
Im trying to write something to get my images to show correctly.
I have 2 numbers "breedtePlaatje" and "hoogtePlaatje". When i load those 2 vars with the values i get back "800" and "500" i expect "verH" to be (500 / 800) = 0,625. Tho the value of verH = 0..
This is the code:
int breedtePlaatje = Convert.ToInt32(imagefield.Width);
int hoogtePlaatje = Convert.ToInt32(imagefield.Height);
//Uitgaan van breedte plaatje
if (breedtePlaatje > hoogtePlaatje)
{
double verH = (hoogtePlaatje/breedtePlaatje);
int vHeight = Convert.ToInt32(verH * 239);
mOptsMedium.Height = vHeight;
mOptsMedium.Width = 239;
//Hij wordt te klein en je krijgt randen te zien, dus plaatje zelf instellen
if (hoogtePlaatje < 179)
{
mOptsMedium.Height = 179;
mOptsMedium.Width = 239;
}
}
Any tips regarding my approach would be lovely aswell.
Dividing int by int gives an int.
double verH = (hoogtePlaatje/breedtePlaatje);
The right hand side of the assignment is an integer value.
Change breedtePlaatje and/or hoogtePlaatje to double and you will get the answer you expect.
Integer division will result in an Integer being returned as the division result.
You need one of the parameters of the division to be a float in order for the result to be a float. You can do this by casting one of them to a float.
double verH = (double)hoogtePlaatje/breedtePlaatje;
Or
double verH = hoogtePlaatje/(double)breedtePlaatje;
See the C# spec regarding division.
When you divide two integers, C# uses integer division, where the fractional part is discarded. In your case you're getting:
500 / 800 = 0 + 5/8
Which, discarding the fractional part, gives:
500 / 800 = 0
To get floating point division, cast one of the arguments to either double, float or decimal depending on the level of precision you need, which will cause the other argument to be implicitly converted to the same type and the division carried out using floating point rules instead of integer rules, e.g.
double result = (double)breedtePlaatje / hoogtePlaatje ;
I have never used C#, but probably you will need to cast one of the variables to double, like this:
double verH = (double)hoogtePlaatje/breedtePlaatje;
Try this:
double verH = double (hoogtePlaatje) / breedtePlaateje;
If you divide an int by an int, you will get a truncated answer. Cast one of them up to a double, and the entire division will be done as double.
To return a double, do I have to cast to double even if types are double?
e.g.
double a = 32.34;
double b = 234.24;
double result = a - b + 1/12 + 3/12;
Do I have to cast (double) ?
No, you don't. However, your expression almost certainly doesn't do what you want it to.
The expressions 1/12 and 3/12 will be performed using integer arithmetic.
You probably want:
double result = a - b + 1/12d + 3/12d;
or
double result = a - b + 1/(double) 12 + 3/(double) 12;
Both of these will force the division to be performed using floating point arithmetic.
The problem here is that if both operands of an arithmetic operator are integers, then the operation is performed using integer arithmetic, even if it's part of a bigger expression which is of type double. Here, your expression is effectively:
double result = a - b + (1 / 12) + (3 / 12);
The addition and subtraction is okay, because the types of a and b force them to be performed using floating point arithmetic - but because division "binds more tightly" than addition and subtraction (i.e. it's like using the brackets above) only the immediate operands are considered.
Does that make sense?
EDIT: As it's so popular, it makes sense to include devinb's comment here too:
double result = a - b + 1.0/12.0 + 3.0/12.0;
It's all the same thing as far as the compiler is concerned - you just need to decide which is clearer for you:
(double) 1
1.0
1d
Nope, no casting is needed.
Of course, there's a clean way to do this without casting:
double result = a - b + 1.0/12 + 3.0/12;
That really depends on what you're asking about casting. Here are two different cases:
double a = 32.34;
double b = 234.24;
double result1 = a - b + 1/12 + 3/12;
double result2 = a - b + (double)1/12 + (double)3/12;
Console.WriteLine(result1); // Result: -201.9
Console.WriteLine(result2); // Result: -201.566666666667
Either way you're not going to get any complaints about assigning the value to result, but in the first case the division at the end is done using integers which resolve to 0.
Hmm - The way that I've done this for the integer division issue is to do something like:
double result = a - b + 1/12.0 + 3/12.0
Aside from those though, no casting would be needed.
You should not need to, although it's hard to tell from your question where the cast would be.
When doing math, C# will return the result as the type of whichever argument has the larger type.
As I recall, the order goes something like this (from largest to smallest):
decimal
double
float
long / int64
int / int32
short / int16
byte
Of course, this is skipping the unsigned versions of each of these.
In general no casting is needed, but in your example, the 1/12 and 3/12 are integer division, resulting in 0 for each expression. You would need to cast one of the numerator or denominator to double.
Casting is used to indicate whenever you want to change one datatype to another type. This is because changing the type usually involves a possible loss of data.
e.g.
double a = 8.49374;
//casting is needed because the datatypes are different.
// a_int will end up with the value is 8, because the precision is lost.
int a_int = (int) a;
double b = (double) a_int;
In that example 'b' will end up with the value of "8.00000..." this is because a_int does not contain ANY decimal information, and so b only has the integer related information at its disposal.