C# 将双精度舍入到 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9295629/
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
Round Up a double to int
提问by markzzz
I have a number ("double") from int/int (such as 10/3).
我有一个来自 int/int 的数字(“double”)(例如 10/3)。
What's the best way to Approximation by Excess and convert it to int on C#?
在 C# 上通过过量近似并将其转换为 int 的最佳方法是什么?
采纳答案by Doug McClean
Are you asking about System.Math.Ceiling?
你在问System.Math.Ceiling吗?
Math.Ceiling(0.2) == 1
Math.Ceiling(0.8) == 1
Math.Ceiling(2.6) == 3
Math.Ceiling(-1.4) == -1
回答by mrbm
Consider 2.42 , you can say it's 242/100 btw you can simplify it to 121/50 .
考虑 2.42 ,您可以说它是 242/100 顺便说一句,您可以将其简化为 121/50 。
回答by EursPravus
int scaled = (int)Math.Ceiling( (double) 10 / 3 ) ;
回答by Ren Wang
By "Approximation by Excess", I assume you're trying to "round up" the number of type double. So, @Doug McClean's "ceiling" method works just fine.
通过“超出的近似值”,我假设您正在尝试“四舍五入”双精度类型的数量。所以,@Doug McClean 的“天花板”方法效果很好。
Here is a note:
If you start with double x = 0.8;and you do the type conversion by (int)x;you get 0. Or, if you do (int)Math.Round(x);you get 1.
If you start with double y = 0.4;and you do the type conversion by (int)y;you get 0. Or, if you do (int)Math.Round(y);you get 0.
这里有一个注意事项:如果您开始double x = 0.8;并通过(int)x;您获得0. 或者,如果你这样做,(int)Math.Round(x);你会得到1. 如果您开始double y = 0.4;并通过(int)y;您获得0. 或者,如果你这样做,(int)Math.Round(y);你会得到0.

