C#递增数组编号

C# Incremented Array Number

好吧,假设我们有一个带有这样数组的变量

int[] digit;
int x = 5; 
for(int i=0;i < = 5; i++)
{ digit[i] = 0;}

var Digit 上的所有值数组都为 0。所以我想做的是我想使用 Button Control 从右边增加该数字的值,增加增量(即意味着数字 [4] 到数字 [3] 等等)并且当值达到数字 [4] 中的某个数字示例 5 时,它将返回值 0 并且下一个 var 数字递增(数字 [3])。然后递增的重新开始等等。

我已经尝试使用 if 和 switch 来实现这一点

private btnClick_Click(Object Sender, Event Args)
{
     digit[4] +=1;
     if(digit[4] > 5) { digit[3] += 1;}
     if(digit[3] > 5) { digit[2] += 1;}
     //and so on
     switch(digit[4])
     {
         case 5: digit[4]=0;
     }
     //and so on
}

但它仅用于逻辑如果我们知道数组编号位置。说如果我检索某个地方的那个号码,比如 15 位数字。如果我们在 命令按钮 上将数组编号设置得太小,它不能填充数组吗?

我已经很困惑地想到了这一点,任何建议、帮助、讨论都将不胜感激。谢谢

如果您只想增加 1,而不是任何减法或增加,比方说 5,我会使用像这样的简单解决方案:

private void btnClick_Click(Object Sender, Event Args) {
    int maxValue = 5;
    int carry = 1; // This is our increment

    // iterate through your digits back to front
    for(int i = digit.Length - 1; i >= 0; i--) {
        digit[i] += carry;  // increase the value by the carry. This will at least increment the last digit by one
        carry = 0;

        // if we reach our max value, we set the carry to one to add it to the next digit, and reset our current digit to 0.
        // If you wanted to increase by more than 1 a time, we would have to add some more calculations here as it would
        // be incorrect to just reset digit[i] to 0.
        if(digit[i] >= maxValue) {
            carry = 1; // the next digit will now be told to increase by one - and so forth
            digit[i] = 0;
        } else {
            break; // This will break out of the for - loop and stop processing digits as everything just fit nicely and we don't have to update more previous digits
        }
    }
}

并不是说一旦你达到 44444 并递增,你最终会得到 00000