Math Operation in Windows Form Application [duplicate] - c#

This question already has answers here:
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 1 year ago.
I am trying to use a function in windows form application that convert a given point to another coordinate system. However, I encountered a strange problem. The input are correct but output is always 0. First, I thought it caused because of the local variables and then instead of variables I used only integers but it did not solve. I have no idea about it. Here the code and output basically:
string[] newPoint1 = convertPoints(X1, Y1);
string[] convertPoints(int oldX, int oldY)
{
//int newX = ((oldX - oldLeft) / (oldRight - oldLeft)) * (newRight - newLeft);
MessageBox.Show(oldX.ToString()); // output is 296
int newX = (oldX / 500) * 4096; // ????????????????????? (296/500) * 4096 = 0 ?????????????
MessageBox.Show(newX.ToString()); // here output is 0
int newY = newTop + ((oldY - oldTop) / (oldBottom - oldTop)) * (newBottom - newTop);
//MessageBox.Show(newY.ToString());
string[] newPoints = {newX.ToString(), newY.ToString()};
//MessageBox.Show(newPoints[0], newPoints[1]);
return newPoints;
}

This is working as it should. Because oldX is an Integer, when you divide it, it rounds (drops anything after the decimal). I would convert it to float and back into an integer, like so
int newX = (int)(((float)oldX / 500) * 4096);
This will preserve the whole number until you're done at the end. You'll also need to do the same for the Y values

An integer division cuts off the decimal places. So in your case, 296/500 you would expect 0.592. As integer has no decimal places, it cuts off them off resulting in 0.
Change the oldX to double and divide by 500.0

You are getting 0 because oldX/500 is a fraction usually and since you are using the int datatypes there can only be whole numbers. What I would recommend doing is changing the data type then rounding yourself.
//Old code
int newX = (1 / 500);
Console.WriteLine(newX);
// writes 0 to console
//New code
double newXD = (1 / 500.0) * 4096;
Console.WriteLine(newXD);
//Writes 8.192
The 1 and the 500 are considered ints try
Console.WriteLine(1/500);
It writes 0 to the console.
Console.WriteLine(1/500.0);
Console.WriteLine((float)1/500);
Console.WriteLine((double)1/500);
All these write 8.192 to the console.
Then after you have the double or other more accurate data type consider rounding if you really want an int.

Related

changing celsius to fahrenheit and vice versa in 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;

Lamda expression not working on String.Count() [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;

basic maths calculations in 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;

Why am I getting 0.0 with this code? [duplicate]

This question already has answers here:
Why I cannot the get percentage by using Int
(9 answers)
Closed 6 years ago.
When I enter, in the Windows Calculator utility, "15036/18218*100=" it returns 82.53375782193435
What I really want is 17.47 (100 - 82.53), but that's beside the point at the moment.
With this code:
// Example: thisQty == 3182; totalQty == 18218
private string GetPercentage(int thisQty, int totalQty)
{
int diff = totalQty - thisQty; // this equates to 15036
double prcntg = (diff/totalQty)*100; // this equates to 0.0 for some reason
return string.Format("{0}%", prcntg);
}
...I'm getting 0.0 for the prcntg value. Why? ISTM that this is the same operation that I'm doing by hand in the Calculator utility. Why doesn't it return 82.53375782193435?
The dividing of 2 ints will be an int even if the correct mathematical answer is with a fraction.
In order to have it keep the decimal part you must divide with a number of a type that holds the fraction part (like double or decimal):
Console.WriteLine(GetPercentage(3182, 18218));
private string GetPercentage(int thisQty, int totalQty)
{
int diff = totalQty - thisQty; // this equates to 15036
double prcntg = (diff / (double)totalQty) * 100;
return string.Format("{0}%", prcntg);
}
BTW - it doesn't matter if you cast to double the diff or the totalQty - for both it will do the / operation returning a double - which means keeping the fraction part
You are using an integer value, (which doesn't store factional part), so cast it to double, or use the parameter type as double (my recommendation). Your operation, 15036/18218 resolves to, 0.82 and in an integer value that is stored as 0... Where finally 0 * 100 is going to resolve to 0 anyways and that is where you get the result.
Try this instead,
private string GetPercentage(double thisQty, double totalQty)
{
double diff = totalQty - thisQty; // this equates to 15036
double prcntg = (diff/totalQty) * 100.0; // this equates to 0.0 for some reason
return string.Format("{0}%", prcntg);
}
This would have the fractional part too and you will get the result.
Based on Gilad Green's answer, here is what I ended up with, which gives the value I ultimately want, and also rounds the value to an integer:
private string GetPercentage(int thisQty, int totalQty)
{
int diff = totalQty - thisQty;
double prcntg = (diff / (double)totalQty) * 100;
prcntg = 100 - prcntg;
int roundedPercent = Convert.ToInt32(prcntg);
return string.Format("{0}%", roundedPercent);
}

math operations always returns 0 c# [duplicate]

This question already has answers here:
C# is rounding down divisions by itself
(10 answers)
C# double not working as expected [duplicate]
(1 answer)
Closed 7 years ago.
I have c# program that calculates percentage and returns int value, but it always returns 0.
I have been writing code for 16 constitutive hours so I appreciate if you find the mistakes within it.
I debugged my code and I found that the value is being passed correctly.
private int returnFlag(int carCapacity, int subscribers)
{
int percentage = (subscribers / carCapacity)*100;
return percentage;
}
What you're seeing is the result of operating on two integers, and losing the fractional portion.
This piece of code, when using the values 5 and 14, will truncate to 0:
(subscribers / carCapacity)
You need to cast one of the operands to a double or decimal:
private int returnFlag(int carCapacity, int subscribers)
{
decimal percentage = ((decimal)subscribers / carCapacity) * 100;
return (int)percentage;
}
The issue is that since you're performing math on int (read: integer) values, any fractions or remainders get thrown out. This can be seen by changing your code to
int percentage = (subscribers / carCapacity);
percentage *= 100;
Since (subscribers / carCapacity) results in less than one, the only possible number an int can hold is 0 - and 0 * 100 is 0.
You can fix this by converting to a more precise number, such as double, before performing operations:
private int returnFlag(int carCapacity, int subscribers)
{
double percentage = ((double)subscribers / (double)carCapacity) * 100.0;
return (int)percentage;
}
Integer types (int) don't work with fractions. Change the types you are working with in your division to decimal, double, single, or float.

Categories