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.
Related
This question already has answers here:
Why do these division equations result in zero?
(10 answers)
Closed 2 years ago.
This:
float a = 2 / 4;
return a;
Will output as 0, while this:
float a = 2;
float b = 4;
float c = a / b;
return c;
Will give a correct output 0.5.
Why am I getting this result?
C# interprets 2 and 4 as plain integers, 2/4 is 0 using integer math (floor of 0.5).
Try using 2f and 4f instead to have floating point numbers. Refer to this documentation to see all possible number literals https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types#real-literals.
Code below works as expected:
public static void Main()
{
float a = 2f / 4f;
Console.WriteLine(a);
}
Because 2 and 4 are the type of integer.
Type type1 = 2.GetType();
Type type2 = 4.GetType();
This question already has answers here:
Why do these division equations result in zero?
(10 answers)
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 4 years ago.
I'm calculating the percentage to add in a datagrid, but when I report the data it always returns me 0, what am I doing wrong?
if I have the following case: the variable quantidadeInstalada has the value of 10 and the goal has 20 the concluido would have to return me 50 but it returns me 0
private void AdicionarPessoa()
{
string Valida = ValidaPessoa();
if (Valida.Equals(""))
{
double concluido=0, falta=0;
int quantidadeInstalada = Convert.ToInt32(ttbQuantidade.Text);
int meta = Convert.ToInt32(ttbMetaPessoa.Text);
concluido = (quantidadeInstalada/meta)*100;
falta = 100-concluido;
MessageBox.Show(concluido.Text);
}
else
MessageBox.Show(Valida);
}
It's probably due to the precision of the int. Use a decimal or double instead.
When we use an integer, we lose precision.
Console.WriteLine(100 / 17); // 5
Console.WriteLine(100 / 17m); // 5.8823529411764705882352941176
Console.WriteLine(100 / 17d); // 5.88235294117647
Console.WriteLine(100 / 17f); // 5.882353
Since integers always round down, 0.99 as an integer is 0.
Note that for precision, the types of the inputs matters.
double output = input1 * input2;
For example:
double outputA = 9 / 10;
Console.WriteLine(outputA); // 0
double outputB = 9 / 10d;
Console.WriteLine(outputB); // 0.9
double outputC = 9d / 10;
Console.WriteLine(outputC); // 0.9
Here is a Fiddle.
It's because you're doing integer division. You can fix it by casting one of the variables to a double like this:
concluido = ((double)quantidadeInstalada/meta)*100;
When you're dividing int by int (as in "quantidadeInstalada/meta"), you'll get an int. Either use a fractional type (e.g. decimal, double) from the very beginning, as Shaun suggested, or (if the integral types have to stay), cast the values to a fractional type in the division expression (as itsme86 shown).
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Division returns zero
simple calculation not working for some reason
Why is this:
int prozent = (totalkcals / 2000) * 100;
returning 0?
totalkcals is in this case 567, I double-checked it.
This is because of integer division
The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs
Its because of Integer division.
double prozent = ((double)totalkcals / 2000) * 100;
567 / 2000 = 0.2835, which when cast to an int (as specified by your data type) becomes zero. 0 * 100 = 0.
So: double prozent = ((double)totalcals / 2000.0) * 100.0;
Its because its an integer calculation, so the operation from (totalkcals / 2000) returns 0;
I was very surprised when I found out my code wasn't working so I created a console application to see where the problem lies and I've got even more surprised when I saw the code below returns 0
static void Main(string[] args)
{
float test = 140 / 1058;
Console.WriteLine(test);
Console.ReadLine();
}
I'm trying to get the result in % and put it in a progress(meaning (140 / 1058) * 100) bar on my application,the second value(1058) is actually ulong type in my application,but that doesn't seem to be the problem.
The question is - where the problem is?
You are using integer arithmetic and then converting the result to a float. Use floating-point arithmetic instead:
float test = 140f / 1058f;
The problem is that you are dividing integers and not floats. Only the result is a float. Change the code to be the following
float test = 140f / 1058f;
EDIT
John mentioned that there is a variable of type ulong. If that's the case then just use a cast opeartion
ulong value = GetTheValue();
float test = 140f / ((float)value);
Note, there is a possible loss of precision here since you're going from ulong to float.
This will work the way you expect ...
float test = (float)140 / (float)1058;
By the way, your code works fine for me (prints a 0.1323251 to the console).
The division being performed is integer division. Replace
float test = 140 / 1058;
with
float test = 140f / 1058;
to force floating-point division.
In general, if you have
int x;
int y;
and want to perform floating-point division then you must cast either x or y to a float as in
float f = ((float) x) / y;