1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Wie viele Gleichungen hat das System? ");
int n = int.Parse(Console.ReadLine());
string[] Variablennamen = new string[n];
double[,] eingang = new double[n, n];
double[] ausgang = new double[n];
for (int i = 0; i < n; i++) //Gleichung einlesen
{
Console.Write("{0}. Gleichung: ", i + 1);
string gleichung = Console.ReadLine();
//rechte Seite der Gleichung abspalten
ausgang[i] = double.Parse(gleichung.Substring(gleichung.IndexOf("=") + 1));
gleichung = gleichung.Remove(gleichung.IndexOf("="));
//es ist nur noch die linke Seite übrig
//Minusvorzeichen zur Zahl ziehen, dazwischen alles mit plus
gleichung = gleichung.Replace("-", "+-");
if (gleichung.Substring(0, 1) == "+") gleichung = gleichung.Remove(0, 1);
string[] summanden = gleichung.Split('+');
foreach (string s in summanden)
{
string variable = s.Substring(s.Length - 1, 1); //letztes Zeichen
string zahl = s.Remove(s.Length - 1);
if (zahl == "") zahl = "1";
if (zahl == "-") zahl = "-1";
//prüfen, ob Variable schon verwendet wurde
for (int j = 0; j < n; j++)
{
if (Variablennamen[j] == null) //wenn Variable bisher noch nicht aufgetaucht
Variablennamen[j] = variable; //anfügen
if (Variablennamen[j] == variable)
{
eingang[i, j] = double.Parse(zahl); //wert für Variable zuweisen
break;
}
}
}
}
//Gleichungssystem lösen mit Gauss
//Dreiecksmatrix erzeugen
for (int i = 0; i < n; i++)
{
if (eingang[i, i] == 0)
{
for(int zeile=i;zeile<n;zeile++)
if(eingang[i,zeile]!=0) //zeile tauschen
{
for (int k = 0; k < n; k++)
{
double tmp = eingang[k, i];
eingang[k, i] = eingang[k, zeile];
eingang[k, zeile] = tmp;
}
double tmp2 = ausgang[i];
ausgang[i]=ausgang[zeile];
ausgang[zeile]=tmp2;
}
}
if (eingang[i, i] == 0) continue;
for (int j = i + 1; j < n; j++)
{
//0er erzeugen durch Addition
double faktor = -eingang[j, i] / eingang[i, i];
for (int k = 0; k < n; k++)
eingang[j, k] += faktor * eingang[i, k];
ausgang[j] += faktor * ausgang[i];
}
}
//einsetzen
double[] erg = new double[n];
for (int i = n - 1; i >= 0; i--)
{
double tmp = ausgang[i];
for (int j = n - 1; j > i; j--)
tmp -= erg[j] * eingang[i, j];
erg[i] = tmp / eingang[i, i];
}
//Ergebnis ausgeben:
for (int i = 0; i < n; i++)
Console.WriteLine("{0} = {1}", Variablennamen[i], erg[i]);
Console.ReadKey();
}
}
} |