如果你想从用户那里得到一个向量,你可以尝试让用户提供它的组件,用一些分隔符分隔,例如
private static int[] ReadVector(string title) {
while (true) { // keep asking user until valid input is provided
if (!string.IsNullOrEmpty(title))
Console.WriteLine(title);
string[] items = Console
.ReadLine()
.Split(new char[] { ' ', '\t', ';', ',' },
StringSplitOptions.RemoveEmptyEntries);
if (items.Length <= 0) {
Console.WriteLine("You should provide at least one component");
continue;
}
bool failed = false;
int[] result = new int[items.Length];
for (int i = 0; i < items.Length; ++i) {
if (int.TryParse(items[i], out int value))
result[i] = value;
else {
Console.WriteLine($"Syntax error in {i + 1} term");
failed = true;
break;
}
}
if (!failed)
return result;
}
}
然后你可以像这样使用这个例程:
// We don't want any 2D matrices here, just 2 vectors to sum
int[] A = ReadVector("Please, enter vector A");
int[] B = ReadVector("Please, enter vector B");
if (A.Length != B.Length)
Console.WriteLine("Vectors A and B have diffrent size");
else {
// A pinch of Linq to compute C = A + B
int[] C = A.Zip(B, (a, b) => a + b).ToArray();
Console.WriteLine($"[{string.Join(", ", A)}] + ");
Console.WriteLine($"[{string.Join(", ", B)}] = ");
Console.WriteLine($"[{string.Join(", ", C)}]");
}
编辑:当然,您可以借助古老的 for 循环而不是 Linq 来对向量求和:
int[] C = new int[A.Length];
for (int i = 0; i < A.Length; ++i)
C[i] = A[i] + B[i];