Multiplication on floating numbers returns unexpected result - c#

int countBouncy=5;
int count=999899;
double percent = (double)(countBouncy / count) * 100.0;
The result of that phrase is unexpected, I get zero.
Why won't it work?

You are doing an integer division on (countBouncy / count). Change your code to
double percent = ((double)countBouncy / count) * 100.0;
That way, countBouncy is converted to double explicitly and count is converted to double implicitly by the c# compiler to make it compatible to the (now double) countBouncy.
Otherwise (countBouncy / count) is calculated as (5 / 999899) --> 0 since both are integers.
How does integer division work? Let's take an example:
7 / 2 = 3
Integer division drops the decimal part that a real division would yield. The result is truncated towards zero. You can get the remainder of this division by using the modulo operator
7 % 2 = 1
and perform the backward calculation like this
2 * (7 / 2) + 7 % 2 = 7
You can enter this in the immediate window of Visual Studio to test it:
?2 * (7 / 2) + 7 % 2<enter>
7

Because your division is integer division, which results in 0, which you then cast into a double.
Your current code is effectively the same as:
int temp = countBouncy / count; // == 0
double percent = (double)temp * 100.0;
Do you cast on one of the items first:
double percent = ((double)countBouncy / count) * 100.0;
That will cause your division to be done in double precision up front.

When you divide an int by an int, the result is always an int, so it's going to round down to the nearest integer (zero). Try this instead:
((double)countBouncy / count) * 100.0;

Your numerator and denominator are both ints. Hence, the resulting quotient is an int which C# calculates by rounding down to 0. Plus, you are trying to assign a double type to an int type. In order to achieve your desired result, do:
double percent = ((double) countBouncy / count) * 100.0;

Related

Divide by 0 error C# [duplicate]

This simple calculation is returning zero, I can't figure it out:
decimal share = (18 / 58) * 100;
You are working with integers here. Try using decimals for all the numbers in your calculation.
decimal share = (18m / 58m) * 100m;
18 / 58 is an integer division, which results in 0.
If you want decimal division, you need to use decimal literals:
decimal share = (18m / 58m) * 100m;
Since some people are linking to this from pretty much any thread where the calculation result is a 0, I am adding this as a solution as not all the other answers apply to case scenarios.
The concept of needing to do calculations on various types in order to obtain that type as a result applies, however above only shows 'decimal' and uses it's short form such as 18m as one of the variables to be calculated.
// declare and define initial variables.
int x = 0;
int y = 100;
// set the value of 'x'
x = 44;
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0. The conversion to double happens
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );
// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
Because the numbers are integers and you perform integer division.
18 / 58 is 0 in integer division.
Whenever I encounter such situations, I just upcast the numerator.
double x = 12.0 / 23409;
decimal y = 12m / 24309;
Console.WriteLine($"x = {x} y = {y}");
double res= (firstIntVar * 100f / secondIntVar) / 100f;
when dividing numbers I use double or decimal , else I am getting 0 , with this code even if firstIntVar && secondIntVar are int it will return the expected answer
decimal share = (18 * 100)/58;
Solved: working perfectly with me
int a = 375;
int b = 699;
decimal ab = (decimal)a / b * 100;

failed/success percentage from total items [duplicate]

This question already has answers here:
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 7 years ago.
Let's assume I have 8 items.
From these 8, 5 are success and 3 failure.
If I want to get the success and failure in percentage with 2 decimals precission I will do like this:
int total = 8;
int success = 5;
int failure = 3;
string success =((decimal)((success * 100) / total)).FormatDecimal();
string failure = ((decimal)((failure * 100) / total)).FormatDecimal();
Format decimal is an extension that will convert decimal to string with x amount of decimals.
public static string FormatDecimal(this decimal value, int decimals = 2)
{
return value.ToString(string.Format("0.{0}", new string('0', decimals)));
}
Now if I take my calculator and I do this, the result is correct:
success: (5 * 100) / 8 = 62.5 %
failure: (3 * 100) / 8 = 37.5 %
However my solution return me 62.00 % and 37.00%
What's wrong with my code?
Because your code is running with integer division but you calculator can do floating-point division.
Your (5 * 100) / 8 returns 62, not 62.5 since both operand is int and this operation will always disregards fractional part.
From / Operator (C# Reference)
When you divide two integers, the result is always an integer. For
example, the result of 7 / 3 is 2.
If you change your total to double, you can fix this since you start doing floating-point division not integer division.
double total = 8.0;
Check out;
7.7.2 Division operator
That's because the division operator / for integers only return the integer part.
If need to cast to float, double or decimal.
var result = ((float)(5 * 100)) / 8;
If any of the values you are dividing is a float, double or decimal, the division operator will support the decimal part.
This is very basic mistake at C#. You have defined the calculation wrong.
(success * 100) / total
It means that after success * 100, the result will be parsed as integer. It is now 300 in integer. 300 / 8 = 37 in integer.
Instead, you can replace the 100 with 100m to force convert them to decimal.

Arithmetic Operation: Int to Double

I am using 2 textboxes and a button in my Windows application.
textBox1 is for user input
textBox2 displays the result of the arithmetic operation.
When the user clicks a button, the following operation should be performed:
1000 * textbox1.text / 60
For this i used
private void button1_Click(object sender, EventArgs e)
{
int Result = 1000 * Convert.ToInt32(textBox1.Text) / 60;
textBox2.Text = Result.ToString();
}
The value I'm getting, however, is an integer, even when I'd expect it to be a double.
How can I fix this?
The rule is:
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.
So all of these will work:
double Result = 1000 * Convert.ToDouble(textBox1.Text) / 60;
double Result = 1000 * Convert.ToInt32(textBox1.Text) / (double)60;
double Result = 1000 * Convert.ToInt32(textBox1.Text) / 60.0;
From MSDN about integer division:
The result is the integer quotient of number1 divided by number2. The
integer quotient discards any remainder and retains only the integer
portion.
You should have at least 1 double on the right side
double Result = 1000 * Convert.ToInt32(textBox1.Text) / 60.0;
Additional note: in order to have a double as a result of an operation like this one, you must give it at least one double, else the right part (1000 * Convert.ToInt32(textBox1.Text) / 60) will just be an integer, THEN converted to a double by the implicit cast from the left part (double Result =).
You're forcing the result to be an integer all the way :
int Result = 1000 * Convert.ToInt32(textBox1.Text) / 60;
You should force Result to be a Double, and force both operands to be doubles :
double Result = 1000 * Convert.ToDouble(textBox1.Text) / 60d;
(60d stands for (double) 60 - I prefer using type suffixes instead of casts, but it is the same)

Unexpected double value in c# [duplicate]

This question already has answers here:
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 9 years ago.
Today i come with a problem and not able to figure out what is the issue with this simple statement
I Tried
double d =1/4;
expected ans for me is 0.25 but in reality ans is 0.0 why so ??
And what should we do if statement is in terms of integer variables like this
double a =(a-b)/(d+e);
Because what you done is here integer division. 1 / 4 always give you 0 as a result regardless which type you assing it.
.NET has 3 type of division. From 7.7.2 Division operator
Integer division
Floating-point division
Decimal division
From Integer division part;
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.
If you want to 0.25 as a result, you should define one of your values as a floating point.
You can use one of these;
double d = 1d / 4d;
double d = 1d / 4;
double d = 1 / 4d;
And what should we do if statement is in terms of integer variables
like this
double a =(a-b)/(d+e);
I assume your a, b, d and e are integers, you should use one of these then;
double a = (double)(a-b) / (double)(d+e);
double a = (a-b) / (double)(d+e);
double a = (double)(a-b) / (d+e);
double d =1d/4;
should work.
If you don't specify the type of your numbers, it is treated as Integer. And integer 1/4 will be zero.
Use this:
double d = (double) 1 / 4;
/ Operator (msdn)
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.
Try this:
double d = 1.0 / 4.0;

Division returns zero

This simple calculation is returning zero, I can't figure it out:
decimal share = (18 / 58) * 100;
You are working with integers here. Try using decimals for all the numbers in your calculation.
decimal share = (18m / 58m) * 100m;
18 / 58 is an integer division, which results in 0.
If you want decimal division, you need to use decimal literals:
decimal share = (18m / 58m) * 100m;
Since some people are linking to this from pretty much any thread where the calculation result is a 0, I am adding this as a solution as not all the other answers apply to case scenarios.
The concept of needing to do calculations on various types in order to obtain that type as a result applies, however above only shows 'decimal' and uses it's short form such as 18m as one of the variables to be calculated.
// declare and define initial variables.
int x = 0;
int y = 100;
// set the value of 'x'
x = 44;
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0. The conversion to double happens
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );
// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
Because the numbers are integers and you perform integer division.
18 / 58 is 0 in integer division.
Whenever I encounter such situations, I just upcast the numerator.
double x = 12.0 / 23409;
decimal y = 12m / 24309;
Console.WriteLine($"x = {x} y = {y}");
double res= (firstIntVar * 100f / secondIntVar) / 100f;
when dividing numbers I use double or decimal , else I am getting 0 , with this code even if firstIntVar && secondIntVar are int it will return the expected answer
decimal share = (18 * 100)/58;
Solved: working perfectly with me
int a = 375;
int b = 699;
decimal ab = (decimal)a / b * 100;

Categories

Resources