c# - 如何将 if else 语句放入循环中
问题描述
这是我的代码。到目前为止,这是可行的,但我需要它处于一个循环中,所以我不会一直重复这if else
句话。
static void Main(string[] args)
{
int i, j, k, l, m, n;
int result;
string [] array = { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" };
i = array[0].Length;
j = array[1].Length;
k = array[2].Length;
l = array[3].Length;
m = array[4].Length;
n = array[5].Length;
result = i * j;
if (result == 16)
{
Console.WriteLine(result);
}
else
{
result = i * k;
}
if (result == 16)
{
Console.WriteLine(result);
}
else
{
result = i * l;
}
if (result == 16)
{
Console.WriteLine(result);
}
else
{
result = i * m;
}
if (result == 16)
{
Console.WriteLine(array[0]+" * "+array[4]+" = "+result);
}
else
{
result = i * n;
}
解决方案
如果您创建一个循环遍历所有条目的外部循环,然后创建一个循环遍历您在外部循环中查看的条目之后的条目的内部循环,您可以执行以下操作
string[] array = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"};
for (var i = 0; i < array.Length; i++)
{
for (var j = i + 1; j < array.Length; j++)
{
if (array[i].Length * array[j].Length == 16)
{
Console.WriteLine($"{array[i]} {array[j]}");
}
}
}
然后你得到的结果是abcw xtfn
推荐阅读
- c++ - 无法通过 Linux 和 C++ 在串行通信中通过 read() 从设备接收消息
- java - 使用 xmlMapper (java) 反序列化 xml 时的问题
- elasticsearch - 应用排序字段后,弹性搜索结果得分为 0
- matrix - Power Bi 计算上个月的增长并在矩阵中显示
- swift - arkit 3d bodytracking 镜子倒置
- docker - 从 PgAdmin4 5.7 中的存储管理器下载文件时出错
- elasticsearch - 如何防止elasticsearch模糊搜索对重复词给出高分
- typescript - 将值数组映射到 Typescript 中的泛型类型
- python - 使用 jinja 2 变量更新 Yaml
- ruby-on-rails - Bundler 不会在 docker 上加载 puma