Simple calculator always return 0 - c#

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.

Related

Dividing two numbers always returns 0 [duplicate]

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).

Convert int to 0-1 float

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.

C# Calculations With Decimal Places

I am having trouble with basic multiplication and division in C#.
It returns 0 for ((150 / 336) * 460) but the answer should be 205.357142857.
I presume this is because (150/336) is a fractional number, and C# rounds this down to 0.
How do I correctly calculate this taking into consideration all decimal places?
No, it is because 150/336 is an integer division which always truncates the decimal part since the result will also be an int.
So one of both must be a decimal number:
double d = 150d / 336;
See: 7.7.2 Division operator
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.
((150 / 336) * 460)
Those numbers are integers, they have no decimal places. Since 150 / 336 evaluates to 0 in integer math, multiplying it by anything will also result in 0.
You need to explicitly make each number a double. Something like this:
((150d / 336d) * 460d)
You are doing integer arithmetic not floating/double. To specify a floating point double constant use the 'd' suffix.
double d = (150d / 336d) * 460d;
150/336 gives you an int as result, thus 0. you need to the division so it you'll have a double as result
(((double)150 / 336) * 460)
If you're using variables then you should write it down like this:
double d = ((double)firstNumber/ secondNumber) * thirdNumber;
For more information: https://www.dotnetperls.com/divide

Dividing by a higher number returning 0

When I try to do this
double test = ((2 / 7) * 100);
it returns 0.
Does anybody know why this is and how to work around it?
Thanks
2 / 7 is integer division, and will return 0. Try this instead
2.0 / 7
(double) 2 / 7
You're dividing integers.
If you want a non-integer result, at least one operand must be a float or double (or decimal).
You can do that by adding .00 to any of the literals to create a literal.
You are dividing integers, so 2 / 7 becomes already 0. Just try 2.0 / 7.0 and you'll get the correct result.
It's doing integer division because all the operands are integers.
To fix it, change at least one the operands to doubles like this:
double test = ((2.0 / 7.0) * 100.0);
You are doing integer math, and only converting to double when you have the final result.
2 / 7 = 0
while
2.0 / 7.0 = 0.285714285714285
Do the math with double values:
double test = ((2.0 / 7.0) * 100.0);
It's because of division. A division of two int numbers returns int number truncating any decimal points. Hence the result of the operation 2/7 will be 0.
It should be something like this:
double test = ((2.0 / 7.0) * 100.0);

Division in c# not going the way I expect

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.

Categories