在 C# 中从两个整数创建百分比值的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2124283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the best way to create a percentage value from two integers in C#?
提问by Vaccano
I have two integers that I want to divide to get a percentage.
我有两个整数要除以得到一个百分比。
This is what I have right now:
这就是我现在所拥有的:
int mappedItems = someList.Count(x => x.Value != null);
int totalItems = someList.Count();
(int)(((double)mappedItems /(double) totalItems) * 100)
This gives the right answer. But that is a lot of casting to do something as simple as get a percentage between two numbers.
这给出了正确的答案。但这需要大量的转换来做一些简单的事情,比如获得两个数字之间的百分比。
Is there a better way to do this? Something that does not involve casting?
有一个更好的方法吗?不涉及铸造的东西?
采纳答案by John Feminella
How about just mappedItems * 100.0 / totalItems
and casting this to the appropriate type?
如何mappedItems * 100.0 / totalItems
将其转换为适当的类型?
回答by Mick
You could use (mappedItems * 100) / totalItems but this would always round down. The method that you have used is better. Why not wrap the code up as a method?
您可以使用 (mappedItems * 100) / totalItems 但这将始终向下取整。您使用的方法更好。为什么不把代码包装成一个方法呢?
回答by tster
Well, assuming your counts are smaller than int.MaxValue:
好吧,假设您的计数小于 int.MaxValue:
int percent = mappedItems * 100 / totalItems;
回答by oefe
If you just wanted to avoid the casts, you could write:
如果你只是想避免强制转换,你可以写:
(100 * mappedItems) / totalItems
but that will quickly overflow when mappedItems > int.MaxValue / 100
.
但是当mappedItems > int.MaxValue / 100
.
And both methods round the percentage down. To get correct rounding, I would keep the result as a double:
并且这两种方法都将百分比向下舍入。为了获得正确的四舍五入,我会将结果保留为双精度:
((double)mappedItems /(double) totalItems) * 100
回答by Guffa
You can get a correctly rounded result using only integer operations:
仅使用整数运算即可获得正确舍入的结果:
int percent = (200 * mappedItems + 1) / (totalItems * 2);
By multiplyingby two, adding one and dividing by two, you are effectively adding a half. This makes the integer division do a rounding instead of truncating.
通过乘以二、加一和除以二,您实际上是加了一半。这使得整数除法进行舍入而不是截断。
回答by ChrisF
Just to add that as you've got int
s and want to calculate the percentage (a floating point value) you are going to haveto do casting. Whether it's explicit as in C# or implicit as in some scripting languages the cast will still happen. It's better to make it explicit.
只是补充一点,因为您有int
s 并且想要计算您将不得不进行转换的百分比(浮点值)。无论是在 C# 中是显式还是在某些脚本语言中是隐式的,转换仍然会发生。最好说清楚。
If you want fewer casts per line of code you could write:
如果您希望每行代码的转换次数更少,您可以编写:
double mappedItems = (double)someList.Count(x => x.Value != null);
double totalItems = (double)someList.Count();
double percentage = (mappedItems / totalItems) * 100.0);
Though as others have pointed out - check for totalItems
being 0 (preferably before casting to double) to avoid a divide by zero.
尽管正如其他人指出的那样 - 检查是否为totalItems
0(最好在强制转换为 double 之前)以避免被零除。
回答by Brad Parks
try this:
尝试这个:
int mappedItems = someList.Count(x => x.Value != null);
int totalItems = someList.Count();
int percent = Convert.ToInt32(complete * 100.0 / total);
in this example, you'd get result being "50"
在这个例子中,你会得到结果是“50”
int mappedItems = 14;
int totalItems = 28;
int result = Convert.ToInt32(mappedItems * 100.0 / totalItems);
// result is 50
回答by dragonroot
The right integer-only way to get percentage with proper rounding is:
通过适当的舍入获得百分比的正确整数方法是:
int result = ( mappedItems * 200 + totalItems ) / ( totalItems * 2 );
How do we get there? If we do this thing in floating point, it would be Math.Floor( mappedItems * 100.0 / totalItems + 0.5 )
. We need to transform this formula to be integer-only by multiplying and dividing 0.5 by totalItems, then moving 0.5 * totalItems into dividend, and then multiplying both dividend and divisor by 2 to make fractions go away:
我们怎么去那里?如果我们用浮点数做这件事,那就是Math.Floor( mappedItems * 100.0 / totalItems + 0.5 )
. 我们需要通过将 0.5 乘以和除以 totalItems,然后将 0.5 * totalItems 移动到被除数,然后将被除数和除数都乘以 2 来使分数消失,从而将这个公式转换为仅整数:
mappedItems * 100.0 / totalItems + 0.5 => mappedItems * 100.0 / totalItems + totalItems * 0.5 / totalItems => ( mappedItems * 100.0 + 0.5 * totalItems ) / totalItems => ( mappedItems * 200.0 + totalItems ) / ( totalItems * 2 ).
映射项目 * 100.0 / 总项目 + 0.5 => 映射项目 * 100.0 / 总项目 + 总项目 * 0.5 / 总项目 => ( 映射项目 * 100.0 + 0.5 * 总项目 ) / 总项目 => (映射项目 * 200.0 + 总项目 *) / (
At this point the formula is integer-only. When we do integer division, we get floored result, so the integer-only result is equivalent to the mentioned floating-point one.
此时,公式仅为整数。当我们做整数除法时,我们得到了地板结果,所以只有整数的结果等价于提到的浮点数。