-1

我这里有一个 C# 控制台应用程序,当我允许用户输入一定数量的记录时,程序会生成一个报价单号。这是为了让我在我的程序中实现它之前测试我制定的算法。

例如,当我输入 23(假设这是数据库中的当前记录数)时,程序将输出“CQ-13-04-0023”。但我得到了“CQ-13-04-0051”的输出。我的目标是当给定报价编号中的序列号达到 9999 时,当数据库中的记录数达到 10000 及以上时,它将重置为 0001。

这是我的代码:

class Program
{
    static void Main(string[] args)
    {
        string QuoteRefNum = "";
        string seriesCount = "";
        DateTime year = DateTime.Now;
        string strYear = year.ToString("yy");
        string strMonth = year.ToString("MM");

        Console.Write("Input the number of records: ");
        int numberOfRecords = Convert.ToInt32(Console.Read());

        numberOfRecords++;

        if (numberOfRecords == 0)
        {
            seriesCount = "000" + numberOfRecords++;
        }
        else if (numberOfRecords >= 1 && numberOfRecords <= 9)
        {
            seriesCount = "000" + numberOfRecords;
        }
        else if (numberOfRecords >= 10 && numberOfRecords <= 99)
        {
            seriesCount = "00" + numberOfRecords;
        }
        else if (numberOfRecords >= 100 && numberOfRecords <= 999)
        {
            seriesCount = "0" + numberOfRecords;
        }
        else if (numberOfRecords >= 1000 && numberOfRecords <= 9999)
        {
            seriesCount = numberOfRecords.ToString();
        }
        else if (numberOfRecords >= 10000 && numberOfRecords <= 99999)
        {
            string newSetOfRecords = numberOfRecords.ToString();
            int tempNumber = 0;

            newSetOfRecords.Remove(0, 1);
            tempNumber = Convert.ToInt32(newSetOfRecords);

            if (tempNumber == 0)
            {
                seriesCount = "000" + tempNumber++;
            }
            else if (tempNumber >= 1 && tempNumber <= 9)
            {
                seriesCount = "000" + tempNumber;
            }
            else if (tempNumber >= 10 && tempNumber <= 99)
            {
                seriesCount = "00" + tempNumber;
            }
            else if (tempNumber >= 100 && tempNumber <= 999)
            {
                seriesCount = "0" + tempNumber;
            }
            else if (tempNumber >= 1000 && tempNumber <= 9999)
            {
                seriesCount = tempNumber.ToString();
            }

        }

        QuoteRefNum = "CQ" + strYear + "-" + strMonth + "-" + seriesCount;

        Console.WriteLine("The quote reference number is: " + QuoteRefNum);
    }
}
4

2 回答 2

1

问题是 Console.Read();当您键入 23 end 时,输入键Read()将返回第一个输入字符的键值,即2. ASCII 字符值为250

所以你会在numberOfRecords++结果之后得到 51

更改 Console.Read();Console.ReadLine();并删除numberOfRecords++

于 2013-04-24T10:34:25.287 回答
1

这条线是问题所在:

        int numberOfRecords = Convert.ToInt32(Console.Read());

它正在返回ASCII值。

将其更改为:

        int numberOfRecords;
        Int32.TryParse(Console.ReadLine(), out numberOfRecords);

并删除numberOfRecords++

解释发生了什么:

你得到的原因51是因为当你输入23的记录数设置为50然后你将变量增加到51vianumberOfRecords++

于 2013-04-24T10:30:06.773 回答