如何用特定参数计算零 [英] How to count zeroes with specific parameters
问题描述
我需要计算零的数量.到目前为止,此代码有效:
I need to count an amount of zeroes. So far this code works:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (uFCheckBox.Checked == true)
{
nFCheckBox.Checked = false;
pFCheckBox.Checked = false;
decimal x = 0;
if (Decimal.TryParse(textBox1.Text, out x))
{
var y = 1000000;
var answer = x * y;
displayLabel2.Text = (x.ToString().Replace(".", "").TrimStart(new Char[] { '0' }) + "00").Substring(0, 2);
string myString = answer.ToString();
// displayLabel5.Text = myString.Split('.')[0].Where(d => d == '0').Count().ToString();
displayLabel5.Text = myString.Split('.')[0].Where(d => d == '0').Count().ToString();
}
当我输入数字(如72、47、83等)时,它完美地计数为零.但是,一旦我输入以零结尾的数字,它便会将其计数为零.我需要一些在前两位数字之后都算为全零的东西.所以50 x 1,000,000将是50,000,000.但我不需要计算前2位数字,因此在这种情况下我需要它输出6. 更多示例:
It counts zero perfectly when I input numbers like 72, 47, 83, etc. But once I input numbers that end with a zero, it counts that zero. I need something that counts all zeroes after the first 2 digits. So 50 x 1,000,000 will be 50,000,000. but I dont need to count the first 2 digits, so I need it to output 6 in this scenario. More example:
1.0 x 1,000,000 = 1,000,000 - I only need to output 5 zeroes
0.10 x 1,000,000 = 100,000 - I only need to output 4 zeroes.
但是我还需要保持一点,如果我输入其他不以零结尾的数字,它仍然可以正确计数. 例子:
But I also need to maintain that if I input other numbers that dont "end" in zeroes it still counts properly. Examples:
72 x 1,000,000 = 72,000,000 - Needs to output 6
7.2 x 1,000,000 = 7,200,000 - Needs to output 5
.72 x 1,000,000 = 720,000 - Needs to output 4
更新: 我现在在使用时会得到正确的输出
Update: I am now getting proper outputs when I use
decimal n = str.Split('.')[0].Substring(2, str.Length - 2).Count( s => s == '0');
但是现在我得到一个错误:索引和长度必须引用字符串中的位置. 参数名称:长度"
but now I get an error: "Index and length must refer to a location within the string. Parameter name: length"
推荐答案
如果我正确理解这一点,则只希望它输出零数.为此,您将执行以下操作:
If I understand this correctly you just want it to output the number of zeros. To do this you would do the following:
var y = 1000000;
var answer = x * y;
string numString = answer.ToString();
char[] charArray = numString.ToCharArray();
int count = 0;
for(int i = 2; i < charArray.Length; i++)
{
if(charArray[i] == '0')
{
count++;
}
}
string output = count.ToString();
使用此方法,输出将是前两位数字之后的零字符串计数.
Using this, output will be the string count of zeros after the first 2 digits.
这篇关于如何用特定参数计算零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!