c# - 在 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
.
解决方案
问题是您以非常不切实际的方式编写它。基本上你有你想要排序的数字集合。
编写数千个if
s 的可读性和可维护性都不是很高。
这里有一个问题:
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));
推荐阅读
- amazon-web-services - 如何使用 javascript 将 AWS Lambda 添加到 VPC
- c# - 如何计算像 MD5(str1+ MD5(str2+ str3)) 这样的哈希值
- c# - 更新条目时出错。有关详细信息,请参阅内部异常有很多关系
- python-3.x - Python 3 TypeError:'int' object is not callable,但这里有什么问题?
- javascript - 为什么我的汉堡菜单示例代码不起作用?
- swiftui - Xcode Playgrounds liveview 无法正常工作,来自 Swift Playgrounds 的代码
- c - 打印时将整数添加到 C-String
- numpy - 如何对分解的张量运算执行 einsum?
- flutter - 如何在 Flutter 的 Stream.periodic 事件中使用动态间隔时间
- c++ - 根据c ++中的特定行对矩阵的列进行排序