【问题标题】:Dividing two numbers [duplicate]将两个数字相除[重复]
【发布时间】:2016-10-12 23:35:47
【问题描述】:

我正在使用 C# 进行一些自学,虽然我做过比这更复杂的项目,但我无法弄清楚问题出在哪里。

    private void button4_Click(object sender, EventArgs e)
    {
        int headcount = 0;
        int input = Global.inputcount;

        for (int i = 0; i < Global.inputcount; i++)
        {
            if (Global.myTextFile[i] == "F")
            {
                headcount++;
            }
        }
        float result;
        result = headcount/input; <<< that line
        button4.Text = result.ToString();
    }

这是我的代码,它应该计算FmyTextFile 数组中出现的次数,它应该将该数字除以输入的数量。

我调试了很多次,直到 [that] 行之前一切都很好。结果为 0,尽管 (headcount = ~2201) 和 (input = ~4321)。

我曾经使用过 Pascal,我已经使用 C# 大约 2 个月了,所以如果有人可以帮助我,我将不胜感激。

F 代表匈牙利语中的“Fej”=“Head”

【问题讨论】:

  • 那是整数除法,使用 result = (float)headcount / input;而是。
  • 问题是整数除法。尝试投射到result = (float)headcount/input;
  • int/int = int - 您需要将设计者 (headcount) 转换为 float
  • 非常感谢!因此,当我使用 f.e. 时,我必须告诉 IDE。输入 a 并期望输入 b 作为结果?
  • 这里有很多相关的问题,我想知道为什么在你输入这个问题的标题时没有一个弹出来。

标签: c# variables


【解决方案1】:

int / int 执行integer division,它总是忽略小数部分无论您分配哪种类型。

来自/ Operator (C# Reference)

当你将两个整数相除时,结果总是一个整数。为了 例如,7 / 3 的结果是 2。要获得商作为有理数 数字或分数,给出被除数或除数类型 float 或 type 双倍。

您可能想改用浮点除法。

result = (float)headcount / input;

result = headcount / (float)input;

同时查看7.7.2 Division operator 文档。

【讨论】:

    【解决方案2】:

    在进行除法之前,您没有将人数或输入值转换为浮点数。它目前正在进行整数除法,不包括任何余数。人数/输入与 2201/4321 相同,在整数除法中等于 0。通过 result = (float)headcount/(float)input 将它们转换为浮点数。

    【讨论】:

      【解决方案3】:

      由于您期望得到INT 结果并且两个操作数都是INT 类型,因此您将得到0 作为输出。您可能希望将其转换为 float 操作

      headcount/(input * 1.0);
      

      【讨论】:

      • 似乎 OP 想要获得人数与总数之间的比率(即期望获得 0 到 1 之间的数字)。另外,请注意,作为 OP,您使用的是整数除法,会丢失除法产生的所有十进制值
      • @GianPaolo,是的,没错。编辑后的答案。
      猜你喜欢
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      • 2015-07-28
      • 2016-02-26
      相关资源
      最近更新 更多