问题
I have an issue with C# not calculating correctly for me to draw my progress bar.
int width = 130;
int maxValue = 20;
int value = 20;
int percent = (width / maxValue) * value
Now it should return 130 so it mean my progress bar is full but it returns 120 so I don't know what is happening.
here is and image of progress bar http://imgur.com/sUbshxk
I also tested the formula with VB.NET and it worked perfectly.
I am using VS2013 in Windows 7 x86.
回答1:
130 / 20
performs integer divison
From / Operator (C# Reference)
When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2
That's why it always discards the fractional part and it returns 6
. That's why your result will be 6 * 20
which is equal to 120
.
As a solution, you can change your integer division to floating-point division.
For example;
var percent = (130.0 / 20) * 20;
var percent = (130 / 20.0) * 20;
That means, you need to define one of your variable as a double
, or cast one of them to double
in your calculation.
回答2:
You need to cast the values to double:
int percent = (int)(((double)width / (double)maxValue) * (double)value);
130 / 20 = 6.5
and it will be implicitely converted to integer
which makes 6
of it. So the wrong value is used for the following multiplication
回答3:
Since you're dividing two int
variables, you're performing integer division.
130/20 is 6.5, which, in integer context is truncated to 6. It is then multiplied by 20, to generate the result of 120.
You could avoid this issue completely by defining your variables as double
s:
double width = 130;
double maxValue = 20;
double value = 20;
double percent = (width / maxValue) * value;
回答4:
In most programming languages, dividing an integer by an integer always results in an integer.
If you don't want an integer result, make sure at least one of the operands is a float or double:
int width = 130;
float maxValue = 20.0;
int value = 20;
int percent = (width / maxValue) * value
来源:https://stackoverflow.com/questions/27216547/c-sharp-bug-or-something-wrong