你如何将它四舍五入到最接近的整数? [英] How do you round it to the closest whole number?

查看:210
本文介绍了你如何将它四舍五入到最接近的整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我写了下面的代码来分割2个数字而没有回答答案:

Hi
I've written the following code to divide the 2 numbers without rounding the answer:

double a, b, c;
            a = double.Parse(textBox1.Text);
            b = double.Parse(textBox2.Text);

            c = a / b;

            label1.Text = c.ToString();



如何使数字更圆?



我尝试过的事情:



我只试过/运营商。我是C#的新手,因此我不知道还能尝试什么。


How do I make it round the number up?

What I have tried:

I've only tried the / operator. I'm new to C# therefore I don't know what else I can try.

推荐答案

首先,不要使用double.Parse来转换用户输入 - 如果他们犯了一个小错误,你的应用程序将崩溃。使用 Double.TryParse方法(String,Double)(系统) [ ^ ]而是:

To start with, don't use double.Parse to convert user input - if they make a single tiny mistake your app will crash. Use the Double.TryParse Method (String, Double) (System)[^] instead:
double a;
if (!double.TryParse(textBox1.Text, out a))
   {
   ... report problem to user ...
   return;
   }
double b;
if (!double.TryParse(textBox2.Text, out b))
   {
   ... report problem to user ...
   return;
   }

请记住,用户一直在输入错误,就像我们一样! :笑:



然后你可以使用 Math.Round方法(双重)(系统) [ ^ ]或 Math.Round方法(Double,Int32)(系统) [ ^ ]舍入计算结果。

Remember, users make typing mistakes all the time, just as we do! :laugh:

Then you can use either the Math.Round Method (Double) (System)[^] or Math.Round Method (Double, Int32) (System)[^] to round the result of your calculation.

label1.Text = Math.Round(a / b).ToString();





BTW:帮自己一个忙,停止使用Visual Studio所有内容的默认名称 - 您可能还记得今天的TextBox8是手机号码,但是当您需要在三周内修改它时,您会这样做吗?使用描述性名称 - 例如tbMobileNo - 您的代码变得更容易阅读,更自我记录,更易于维护 - 并且编码速度更快,因为Intellisense可以通过三次击键来tbMobile,其中TextBox8需要思考大概和8次击键......



BTW: Do yourself a favour, and stop using Visual Studio default names for everything - you may remember that "TextBox8" is the mobile number today, but when you have to modify it in three weeks time, will you then? Use descriptive names - "tbMobileNo" for example - and your code becomes easier to read, more self documenting, easier to maintain - and surprisingly quicker to code because Intellisense can get to to "tbMobile" in three keystrokes, where "TextBox8" takes thinking about and 8 keystrokes...


Math.Ceiling方法(系统) [ ^ ]


这篇关于你如何将它四舍五入到最接近的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆