gpt4 book ai didi

c# - 如何停止从 C# 中的整数中删除前导 0

转载 作者:太空宇宙 更新时间:2023-11-03 17:20:56 27 4
gpt4 key购买 nike

我正在尝试存储表示 4 位字符串的整数,其中一些字符串的开头为 0。当我在控制台中写出这些值时,前导 0 被剥离,我可以阻止这种情况发生吗?我通读了文档,但看不到任何可以阻止这种情况发生的内容。到目前为止,这是我的代码:

class Fitness
{
Random random = new Random();

int[] myArray = new int[15];
int[] myArray2 = new int[6];
int[] numbers = new int[6];
int randomNumber;
public void setup()
{

for (int i = 0; i < 6; i++)
{
do
{
randomNumber = random.Next(1, 16);
}
while (numbers.Contains(randomNumber));

numbers[i] = randomNumber;

}
Array.Sort(numbers);
foreach (int i in numbers)
{
Console.WriteLine(i);
}
Console.WriteLine("-----------------");
Console.WriteLine("-----------------");

myArray[0] = 0001;
myArray[1] = 0010;
myArray[2] = 0011;
myArray[3] = 0100;
myArray[4] = 0101;
myArray[5] = 0110;
myArray[6] = 0111;
myArray[7] = 1000;
myArray[8] = 1001;
myArray[9] = 1010;
myArray[10] = 1011;
myArray[11] = 1100;
myArray[12] = 1101;
myArray[13] = 1110;
myArray[14] = 1111;

for (int i = 0; i < 6; i++)
{
myArray2[i] = myArray[numbers[i]-1];
}
foreach (int i in myArray2)
{
Console.WriteLine(i);
}
}
}

最佳答案

Int32 没有前导零string 可以有。您需要应用正确的格式。您可以在 ToString 中使用十进制 ("D") 格式说明符:

 foreach (int i in myArray2)
{
Console.WriteLine(i.ToString("d4"));
}

Standard Numeric Format Strings

The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. If no precision specifier is specified, the default is the minimum value required to represent the integer without leading zeros.

关于c# - 如何停止从 C# 中的整数中删除前导 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16059056/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com