首页 > 解决方案 > 在 C# 中使用 If else 升序排列 5 个数字

问题描述

我想知道问题出在哪里,我可以解决这个问题。

        int a = 15, b = 5, c = 1, d = 30, e = 25;
        int num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0;

        // checking value of A against the other fourth values
        if (a < b && a < c && a < d && a < e)
            num1 = a;

        if (a > b && a < c && a < d && a < e)
            num1 = b;

        if (a > b && a > c && a < d && a < e)
            num1 = c;

        if (a > b && a > c && a > d && a < e)
            num1 = d;

        if (a > b && a > c && a > d && a > e)
            num1 = e;

        // checking value of B against the other fourth values
        if (b < a && b < c && b < d && b < e)
            num2 = a;

        if (b > a && b < c && b < d && b < e)
            num2 = b;

        if (b > a && b > c && b < d && b < e)
            num2 = c;

        if (b > a && b > c && b > d && b < e)
            num2 = d;

        if (b > a && b > c && b > d && b > e)
            num2 = e;

        // checking value of C against the other fourth values
        if (c < a && c < b && c < d && c < e)
            num3 = a;

        if (c > a && c < b && c < d && c < e)
            num3 = b;

        if (c > a && c > b && c < d && c < e)
            num3 = c;

        if (c > a && c > b && c > d && c < e)
            num3 = d;

        if (c > a && c > b && c > d && c > e)
            num3 = e;

        // checking value of D against the other fourth values
        if (d < a && d < b && d < c && d < e)
            num4 = a;

        if (d > a && d < b && d < c && d < e)
            num4 = b;

        if (d > a && d > b && d < c && d < e)
            num4 = c;

        if (d > a && d > b && d > c && d < e)
            num4 = d;

        if (d > a && d > b && d > c && d > e)
            num4 = e;

        // checking value of E against the other fourth values
        if (e < a && e < b && e < c && e < d)
            num5 = a;

        if (e > a && e < b && e < c && e < d)
            num5 = b;

        if (e > a && e > b && e < c && e < d)
            num5 = c;

        if (e > a && e > b && e > c && e < d)
            num5 = d;

        if (e > a && e > b && e > c && e > d)
            num5 = e;

        Console.WriteLine("Ranks from Lowest to Highest" + num1 + " " + num2 + " " + num3 + " " + num4 + " " + num5);


        Console.ReadKey();

输出应该是Ranks from Lowest to Highest 1, 5, 15, 25, 30,但是当我运行控制台时,输出是Ranks from Lowest to Highest 0, 15, 25, 30.

标签: c#

解决方案


问题是您以非常不切实际的方式编写它。基本上你有你想要排序的数字集合。

编写数千个ifs 的可读性和可维护性都不是很高。

这里有一个问题:

Console.WriteLine("Ranks from Lowest to Highest" + num1 + " " + num2 + " " + num3 + " " + num4 + " " + num5);

与您的输出不匹配:

Ranks from Lowest to Highest 0, 15, 25, 30

因为您正在打印 5 个数字,而您的输出仅显示 4 个......所以它不能是您的实际输出。

有一种使用集合对数字进行排序的非常干净的方法,例如Array借助 LINQ 扩展方法:

int[] array = new int[] {a, b, c, d, e };
Console.WriteLine("Ranks from Lowest to Highest:");
array.OrderBy(i => i).ForEach(i => Console.WriteLine(i));

推荐阅读