Skip to main content
 首页 » 编程设计

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

2024年02月13日16artech

我正在尝试使用 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 不能。亲自尝试。