如何在C#中使用'for循环'和'array'反转整数 [英] How to Reverse integers using 'for loop' and an 'array' in C#

查看:136
本文介绍了如何在C#中使用'for循环'和'array'反转整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,我正在学习反转整数(数字).我必须使用forloop和数组来完成代码,但我真的不知道如何使用这些代码.
例如.如果输入为:1 2 3 4 5 6
结果应为:6 5 4 3 2 1

I am new to C# and I am learning to reverse integers (numbers). I have to use forloop and an array to complete the code but i really have no idea how to use those.
For example. If the input is: 1 2 3 4 5 6
Results should be : 6 5 4 3 2 1

有人可以帮助我吗?谢谢:)

Can someone please help me. Thank you :)

非常抱歉,我忘记添加代码了.这里是.再次感谢

I am really sorry guys, I forgot to add the code. Here it is. Thanks again

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();
}

修改

此处将字符串作为输入,并且需要反转.只是由于输入仅被视为数字,所以这有点令人困惑.

Here a string is taken as input and need to be reversed. Just due to the input is taken as numbers only so this is confusing little bit.

推荐答案

除非需要使用循环,否则更简单的解决方案是使用

Unless you need to use a loop, a much simpler solution is to use Array.Reverse:

int[] array = { 1, 2, 3, 4, 5, 6 };
Array.Reverse(array);

您可以使用for循环并迭代数组的一半,并用数组另一侧的位置切换位置.

You could use a for loop and iterate half of the array, switching the positions with the ones on the opposite side of the array.

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;
}

这篇关于如何在C#中使用'for循环'和'array'反转整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆