所以,很快。是否可以在列表中插入双精度AND字符串?像这样:
if (input2 == 0) // this boolean checks if the first number is devided by zero, then:
{
listOfResults.Insert(index: temp, item: "You divided by 0! Wait, thats illegal"); // and thats what i want, to add a string into the position of the list when the input is 0
}
else
{
result = (double)input1 / (double)input2; // the input numbers are int but i cast them to double
listOfResults.Insert(index: position, item: result);
}
我的输入是:3和2、6和3,-4和0、1和2,我用第二个输入数字表示每个第一个数字。输出应为:
1.52您除以0!等等,那是非法的0.5那么是否可以在列表中为每个位置存储双精度AND字符串?
列表将允许两种类型。例如,在使用值时,可以使用typeof()== typeof(double),也可以仅使用ToString()。
是的,您可以创建一个List ,它可以包含任何数据类型,双精度,字符串,整数,其他对象等。
更好的选择可能是定义一个Result对象,例如
class Result
{
public bool Error { get; set; } = false;
public double Value { get; set; }
public string ErrorMessage { get; set; } = "";
}
然后存储List 的列表,这样就无需转换或检查类型。
您可以使用元组列表:
var tupleList = new List<(double, string)>();
tupleList.Add((2.5, "a string"));
这是我会给你的代码的地方:
var listOfResults = new List<(double? result, string error)>();
if (input2 == 0)
{
listOfResults.Insert(index: temp, item: (null, "You divided by 0! Wait, thats illegal"));
}
else
{
result = (double)input1 / input2;
listOfResults.Insert(index: position, item: (result, null));
}
这是打印输出的方法:
foreach (var item in listOfResults)
{
if (item.result.HasValue)
Console.WriteLine(item.result);
else
Console.WriteLine(item.error);
}