[英]How to Display Array Values using Nested For loops?
在我们开始之前,我是编程和 C# 语言的新手,所以请耐心等待。 我遇到的问题是像这样在彼此面前显示两个单独的数组值:
整数类型:sbyte、byte、short、ushort
Real 浮点类型:float、double
我试过的代码是:
string[] VariableTypes = { "Integer Type", "Real Floating Point Types" };
string[] IntergerTypes = { "sbyte", "byte", "short", "ushort" };
for (int i = 0; i <= VariableTypes.Length - 1; i++)
{
for(int j=0; j<=IntergerTypes.Length - 1; j++)
{
Console.Write(IntergerTypes[j] + " ");
}
Console.WriteLine(VariableTypes[i] + " : ");
}
我得到的输出:
sbyte byte short ushort 整数类型:
sbyte byte short ushort 实数浮点类型:
您需要另一个数组来保存要与Real Floating Point Types
相关的值,然后有条件地检查变量类型以查看与之关联的整数类型。
string[] VariableTypes = { "Integer Type", "Real Floating Point Types" };
string[] FloatingPointTypes = { "float", "double" };
string[] IntergerTypes = { "sbyte", "byte", "short", "ushort" };
for (int i = 0; i <= VariableTypes.Length - 1; i++)
{
Console.WriteLine(VariableTypes[i] + " : ");
if(VariableTypes[i] == "Integer Type")
{
for(int j=0; j<=IntergerTypes.Length - 1; j++)
{
Console.Write(IntergerTypes[j] + ", ");
}
}
else
{
for(int j=0; j<=FloatingPointTypes.Length - 1; j++)
{
Console.Write(FloatingPointTypes[j] + ", ");
}
}
}
在我看来,如果您只想要一种实现上述输出的方法,那么在没有嵌套循环的情况下这样做会更干净:
string[] FloatingPointTypes = { "float", "double" };
string[] IntergerTypes = { "sbyte", "byte", "short", "ushort" };
Console.WriteLine("Integer Type: " + string.Join(", ", IntergerTypes));
Console.WriteLine("Real Floating Point Types: " + string.Join(", ", FloatingPointTypes));
另外,您可以利用一个类使您的工作更简化。 请参阅以下内容:
public class VariableType
{
public string Name { get; set; }
public List<string> DataTypes { get; set; }
}
并通过以下步骤使用该类来实现所需的结果:
var variableTypes = new List<VariableType>
{
new VariableType
{
Name = "Integer Types",
DataTypes = new List<string>{ "sbyte", "byte", "short", "ushort" }
},
new VariableType
{
Name = "Real Floating Point Types",
DataTypes = new List<string>{ "float", "double" }
}
};
foreach(var variableType in variableTypes)
{
Console.WriteLine(variableType.Name + " : " + string.Join(", ", variableType.DataTypes));
}
string[] VariableTypes = {
"Integer Type", "Real Floating Point Types"
};
string[][] NumberTypes = {
new string[] { "sbyte", "byte", "short", "ushort" },
new string[] { "float", "double" }
};
for (int i = 0; i < VariableTypes.Length; i++)
{
Console.Write(VariableTypes[i] + " : ");
for(int j = 0; j < NumberTypes[i].Length; j++)
{
Console.Write(NumberTypes[i][j] + " ");
}
Console.WriteLine();
}
这是实现此目的的简短方法:
string[] VariableTypes = { "Integer Types", "Real Floating Point Types" };
string[] IntegerTypes = { "sbyte", "byte", "short", "ushort" };
string[] RealFloatingPointTypes = { "float", "double" };
Console.WriteLine(String.Concat(VariableTypes[0], " : ", String.Join(", ", IntegerTypes)));
Console.WriteLine(String.Concat(VariableTypes[1], " : ", String.Join(", ", RealFloatingPointTypes)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.