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.
Related
How come dividing two 32 bit int numbers as ( int / int ) returns to me 0, but if I use Decimal.Divide() I get the correct answer? I'm by no means a c# guy.
int is an integer type; dividing two ints performs an integer division, i.e. the fractional part is truncated since it can't be stored in the result type (also int!). Decimal, by contrast, has got a fractional part. By invoking Decimal.Divide, your int arguments get implicitly converted to Decimals.
You can enforce non-integer division on int arguments by explicitly casting at least one of the arguments to a floating-point type, e.g.:
int a = 42;
int b = 23;
double result = (double)a / b;
In the first case, you're doing integer division, so the result is truncated (the decimal part is chopped off) and an integer is returned.
In the second case, the ints are converted to decimals first, and the result is a decimal. Hence they are not truncated and you get the correct result.
The following line:
int a = 1, b = 2;
object result = a / b;
...will be performed using integer arithmetic. Decimal.Divide on the other hand takes two parameters of the type Decimal, so the division will be performed on decimal values rather than integer values. That is equivalent of this:
int a = 1, b = 2;
object result = (Decimal)a / (Decimal)b;
To examine this, you can add the following code lines after each of the above examples:
Console.WriteLine(result.ToString());
Console.WriteLine(result.GetType().ToString());
The output in the first case will be
0
System.Int32
..and in the second case:
0,5
System.Decimal
I reckon Decimal.Divide(decimal, decimal) implicitly converts its 2 int arguments to decimals before returning a decimal value (precise) where as 4/5 is treated as integer division and returns 0
You want to cast the numbers:
double c = (double)a/(double)b;
Note: If any of the arguments in C# is a double, a double divide is used which results in a double. So, the following would work too:
double c = (double)a/b;
here is a Small Program :
static void Main(string[] args)
{
int a=0, b = 0, c = 0;
int n = Convert.ToInt16(Console.ReadLine());
string[] arr_temp = Console.ReadLine().Split(' ');
int[] arr = Array.ConvertAll(arr_temp, Int32.Parse);
foreach (int i in arr)
{
if (i > 0) a++;
else if (i < 0) b++;
else c++;
}
Console.WriteLine("{0}", (double)a / n);
Console.WriteLine("{0}", (double)b / n);
Console.WriteLine("{0}", (double)c / n);
Console.ReadKey();
}
In my case nothing worked above.
what I want to do is divide 278 by 575 and multiply by 100 to find percentage.
double p = (double)((PeopleCount * 1.0 / AllPeopleCount * 1.0) * 100.0);
%: 48,3478260869565 --> 278 / 575 ---> 0
%: 51,6521739130435 --> 297 / 575 ---> 0
if I multiply the PeopleCount by 1.0 it makes it decimal and division will be 48.34...
also multiply by 100.0 not 100.
If you are looking for 0 < a < 1 answer, int / int will not suffice. int / int does integer division. Try casting one of the int's to a double inside the operation.
The answer marked as such is very nearly there, but I think it is worth adding that there is a difference between using double and decimal.
I would not do a better job explaining the concepts than Wikipedia, so I will just provide the pointers:
floating-point arithmetic
decimal data type
In financial systems, it is often a requirement that we can guarantee a certain number of (base-10) decimal places accuracy. This is generally impossible if the input/source data is in base-10 but we perform the arithmetic in base-2 (because the number of decimal places required for the decimal expansion of a number depends on the base; one third takes infinitely many decimal places to express in base-10 as 0.333333..., but it takes only one decimal in base-3: 0.1).
Floating-point numbers are faster to work with (in terms of CPU time; programming-wise they are equally simple) and preferred whenever you want to minimize rounding error (as in scientific applications).
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.
In my C# application I want to implement a simple calculation. I got this code:
private void button1_Click(object sender, EventArgs e)
{
int percentField;
int priceField;
int result;
percentField = int.Parse(txtPercentNew.Text);
priceField = int.Parse(txtPriceNew.Text);
result = priceField / 100 * percentField;
MessageBox.Show(result.ToString());
}
But the problem is the MessageBox displays me 0. I can't figure out why.
Can someone please give me a hint what I am doing wrong?
Your variables are integers, which means that / performs integer division. Unless priceField is at least equal to 100 you will always get 0 as the result.
You can correct the problem by casting priceField to a floating point type before dividing:
(double)priceField / 100 * percentField;
However, this will not work while result is of type int because the compiler wants to protect you from inadvertent rounding errors. So you either have to cast back to an integer (losing precision due to rounding):
result = (int)((double)priceField / 100 * percentField);
or else make result be a double as well.
You are using integers instead of floating point numbers.
As a consequence, rounding off occurs during calculation.
Use float or double instead of int.
Probably your priceField is less then 100 and since you doing integer division, it creates 0 as a result.
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 determine the remainder of 7 /
3, use the remainder operator (%). To obtain a quotient as a rational
number or fraction, give the dividend or divisor type float or type
double. You can assign the type implicitly if you express the dividend
or divisor as a decimal by putting a digit to the right side of the
decimal point, as the following example shows.
Just cast one of your variables to floating point type like;
result = priceField / 100d * percentField;
or
result = (double)priceField / 100 * percentField;
You are working with only integers, try
double result;
result = priceField / (double)100 * percentField;
In your code, you are dividing by 100. Which means every int you are going to divide less than 100 will result in a value between [0 - 1]. When implicitly casting to an int, the result will be floored. Therefor, a 0.1 will become 0 - a 0.9 will become 0 - ...
try cast to double, because you're working with integers it results in 0.
example here
The problem is you're using int for each value.
Change result to a double and try this:
result = (double)priceField / 100 * percentField;
It should work; however, if you want to do this properly I recommend you read about MidpointRounding.
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).
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.