C# 需要帮助确保将多次出现的同一字母标记为数字

C# need help making sure multiple occurrences of the same letter are noted as a number

我正在用 C# 为我的学校项目编写定期 table。 我想这样做,如果我按下(例如)H 按钮 3 次,它就会显示为 H3。它现在只适用于 H2,我不知道为什么?欢迎任何帮助,在此先感谢。

    private void btn_H_Click(object sender, EventArgs e)
    {
        txt_Chemical.Text = txt_Chemical.Text + "H";
        txt_Mass.Text = txt_Mass.Text + 1.006;
        int count = txt_Chemical.Text.TakeWhile(c => c == 'H').Count();
        if(count > 1)
        {
            txt_Chemical.Text = "H" + count;
            txt_Mass.Text = txt_Mass.Text + 1.006 * count;
        }
    }

我现在无法验证它是否属实,但请尝试:

我认为(最多按两次 H 键)可能是由于您代码中的这一行:

int count = txt_Chemical.Text.TakeWhile(c => c == 'H').Count();

TakeWhile 的工作原理如下 - 它从头开始遍历列表,并在第一次出现不满足谓词的情况时停止。 .

所以当你这样做时:

txt_Chemical.Text = "H" + count;

你的第三个字母成为计数持有的价值。所以下次 TakeWhile 在第二个元素上中断时 "HH2".TakeWhile(c => c == 'H') 产生两个元素集合。

尝试使用单独的变量来保存状态(H 被点击的次数)。

另外:

  • count 之前使用 var 而不是 int - 如果您稍后更改类型,它会有所帮助
  • 如果您关心精度 - 我假设您关心的是化学品,请不要使用双精度 (1.006)。使用保证精度 (1.006m) 的小数。