c# - 当输入和输出应该是整数时,如何保存中间小数结果?

标签 c# types casting

我正在尝试使用 C# 创建 BMI 计算器。

My formula is BMI = (weight /(height * height)) * factor.
Example:      BMI = (172 / (73 * 73 )) * 703
              BMI = (172 / 5329) * 703
              BMI = ( 0.032) * 703
              BMI =   22.69

我的问题是,在我用体重除以高度后得到一个分数,尽管当我用它乘以大于 1 的因子时,我无法将它保存在我的整数变量中。所以我的总 BMI 始终为 0。

我需要重新考虑我的数据类型吗?还是我应该转换它们?我不确定如何解决这个问题。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Calculate_Click(object sender, EventArgs e)
    {
        int feet, inches, height, pounds, result, factor;
        factor = 703;

        //convert the text input to the correct data type
        feet = Convert.ToInt32(feetBox.Text);
        inches = Convert.ToInt32(inchesBox.Text);
        pounds = Convert.ToInt32(poundsBox.Text);

        //turn the feet and inches into a single height value in inches
        height = (feet * 12) + inches;

        //calculate the BMI
        //result = (pounds / (height * height) ) * factor;
        result = factor * (pounds / (height * height));

        // output the results
        output.Text = String.Format("Your BMI is: {0}", result);
    }
}

最佳答案

您面临整数除法。如果将整数除以整数,结果又是整数。要解决此问题,您必须将值转换为浮点类型(float/double)。这将解决问题。

double result = factor * (pounds/(double)(height * height));

这样您将强制结果为十进制数。

编辑: 问题如下。将整数想象成物理对象 - 例如苹果。

7/3 你有 7 个苹果,你想送给 3 个 child 。每个 child 会得到多少个苹果?答案是 2。余数当然是1。但整数除法不返回余数,因此该信息在除法过程中“丢失”了。

在编程时,经验法则是尽可能坚持使用整数。由于十进制数在内存中的存储方式,存在一些错误。请注意,在不损失精度的情况下,最多可以将一些任意值整数存储在浮点类型中,但从阈值开始,即使是整数也存在错误。 在下面的浮点转换器中尝试 123456789,它不会被准确存储,这就是为什么最好尽可能长时间地坚持使用整数。

检查这些缺陷的好工具是这个 float converter 。例如 0.5 可以精确存储,但 0.6 不能。亲自尝试。

关于c# - 当输入和输出应该是整数时,如何保存中间小数结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19314104/

相关文章:

c# - 创建引用 ActionFilters、HTTPContext、HTTPException 等的 .Net Standard 库

javascript - typescript 类型的动态类方法

go - 如何在 Go 中创建多级错误子类型

Java ArrayUtils.toPrimitive 我不能做 ArrayUtils.removeElement

Java:用 try catch block 函数包装代码?

c# - 仅在 C# 中验证 XML 语法

c# - 如何从 WPF MVVM 中的用户控件创建 PDF

c# - VS2010 上的 TFS,合并代码问题

list - 在 F# 中合并有序列表,需要 'a but given a ' a -> a' 列表

ios - 从 Parse 中获取子类对象