问题
Please forgive my programming knowledge. I know this is a simple thing, but I do not understand why result is always 0. Why decimal will be fine?
int a = 100;
int b = 200;
decimal c = (a / b) * 100;
Many thanks.
回答1:
Integer division always truncates the remainder. This is done at the time that the number is divided, not when it's assigned to the variable (as I'm guessing you assumed).
decimal c = ((decimal)a / b) * 100;
回答2:
The value a/b will return 0 always since they are integers. So when the values within the Brackets are evaluated you are technically doing this
decimal c = (0) * 100
Better do,
decimal c = ((decimal)a/(decimal)b) * 100
回答3:
100 / 200 is 1/2 or 0.5. Since you are using ints, it rounds down to 0 (zero). And 0 * 100 is still 0. The part inside the parentheses is always evaluated first: if you want to get this working, use:
decimal c = (a * 100) / b;
Edit: if you want a more precise value rather than an "integer percentage" (ie. 33.333% instead of 33%), you should use Bragaadeesh's answer.
回答4:
Integer math is being performed, and the result is then being stored as a decimal. 100 / 200 in integer math is 0. To get your percentage, cast at least one value to decimal before doing the calculation.
decimal c = (a / (decimal)b) * 100;
回答5:
In strongly typed languages, the result of math operations is usually the same type as the larger type.
C# has a list of implicit numeric conversions it will do.
Generalizing this list: Integral types can be converted to floating point types, but not vice versa. Integral types can also be implicitly converted to decimal
, but floating point types cannot.
Note: This also means that casting one of the ints to another type will result in the entire answer being that type.
ex: (decimal) a / b * 100.0 = 50.0
tl;dr:
In C#:
int / int = int
int + decimal = decimal
decimal + int = decimal
int / int * decimal = (int / int = int) * decimal = decimal
int - float = float
int * double = double
float / decimal = an error
int - uint = an error (either that or ulong)
回答6:
The math being done is still integer math.
(a/b) (100/200 or 1/2) is done on two integers, so the result is zero. Zero * 100 is ... well, still zero.
The problem you are experiencing is with the order of operations (a and b are integers, so integer math is performed).
I suggest this:
decimal c=((decimal)a)/((decimal)b)*100;
This will force the math performed to the decimal values you seek.
回答7:
int can only be whole numbers, so 100/200 is going to be 0. 0*100 is still 0. Change the type to a decimal, and it will work
回答8:
Make it decimal c = (a * 100) / b;
回答9:
While using integers, this '/' stands for DIV and this '%' for MOD. DIV is the quotient of the division, MOD is the rest. So, 100/200 = 0 and 100%200 = 100.
So, you need to change a
and b
types to decimal
, in your case.
来源:https://stackoverflow.com/questions/2602025/why-i-cannot-the-get-percentage-by-using-int