我是C#的新手,我正在学习反转整数(数字)。我必须使用forloop和数组来完成代码,但我真的不知道如何使用它们。 例如。如果输入为:1 2 3 4 5 6 结果应为:6 5 4 3 2 1
有人可以帮助我。谢谢:))
编辑:我真的很抱歉,我忘了添加代码。这里是。再次感谢static void Main(string[] args)
{
Console.WriteLine("Enter 6 Numbers");
int numb = int.Parse(Console.ReadLine());
int reverse = 0;
while (numb > 0)
{
int rem = numb % 10;
reverse = (reverse * 10) + rem;
numb = numb / 10;
}
Console.WriteLine("The reverse is = {0}", reverse);
Console.ReadLine();
}
答案 0 :(得分:4)
除非您需要使用循环,否则更简单的解决方案是使用Array.Reverse
:
int[] array = { 1, 2, 3, 4, 5, 6 };
Array.Reverse(array);
您可以使用for循环并迭代一半数组,使用数组另一侧的位置切换位置。
int holder = 0;
int size = array.Length;
for (int i = 0; i < size / 2; ++i)
{
holder = array[i];
array[i] = array[size - 1 - i];
array[size - 1 - i] = holder;
}
答案 1 :(得分:0)
这对我不起作用?
int[] array = new int[4];
int getlength = array.Length;
int k = getlength - 1;
array[0] = 100;
array[1] = 500;
array[2] = 700;
array[3] = 900;
for (int j = 0; j < array.Length; j++)
{
Console.WriteLine(array[j]);
}
Console.ReadLine();
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(k);
Console.ReadLine();
array[i] = array[k];
k--;
Console.WriteLine(array[i]);
}
Console.ReadLine();
答案 2 :(得分:0)
这是使用循环反转数字/整数并使用Array.Reverse功能的简单逻辑
示例:输入12345将为我们提供54321
的输出namespace PurushLogics
{
class Purush_ReverseInteger
{
static void Main()
{
//Reverse a Number
int intstr;
string intreverse = "";
int intLength = 0;
int? intj = null;
Console.WriteLine("Enter a Number"); // Entering "12345" has input will return "54321" as output
intstr = int.Parse(Console.ReadLine());//Getting integer from Console
char[] inta = intstr.ToString().ToCharArray();
intLength = inta.Length - 1;
for (int c = intLength; c >= 0; c--)
{
intreverse = intreverse + inta[c].ToString();
intj = int.Parse(intreverse);
}
Console.WriteLine("Reverse Number is \"{0}\"", intj);//Displaying the reverse integer
Console.ReadLine();
//Reverse integer using Array.Reverse
Array.Reverse(inta);
foreach (char reverse in inta)
{
Console.Write(reverse);
}
Console.ReadLine();
}
}
}
答案 3 :(得分:0)
static void Main(string[] args)
{
int[] numbers = new int[6];
for (int i = 0; i < 6; i++)
{
Console.Write("Number {0} : ", i + 1);
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine();
for (int i = 5; i >= 0; i--)
{
Console.Write("{0} ", numbers[i]);
}
Console.ReadLine();
}
答案 4 :(得分:-1)
class Program
{
static void Main(string[] args)
{
int[] array = new int[] { 1, 2, 3, 4, 5, 6,7};
int temp = 0;
for (int i = array.Length - 1; i >= (((array.Length - 1) % 2==0)? (((array.Length - 1) / 2)):((array.Length - 1) / 2)+1) ; i--)
{
temp = array[(array.Length - 1) - i];
array[(array.Length - 1) - i] = array[i];
array[i] = temp;
}
foreach (var p in array)
{
Console.WriteLine(p);
}
Console.ReadLine();
}
}
答案 5 :(得分:-1)
int[] numbers=new int[]{1,2,3,4,5};
int[] reverse=new int[numbers.Length];
int j=numbers.Length-1;
for(int i=0;i<numbers.Length;i++)
{
reverse[i]=numbers[j];
Console.WriteLine(reverse[i]);
j--;
}