Толковое объяснение здесь: https://metanit.com/
Свой пример (см. строки 15, 29-38, 45):
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; using System.Threading.Tasks; using System.IO; // Программа нахождения минимума функции на указанном отрезке // На выбор 2 функции namespace DoubleBinary { class Program { delegate double Function(double a, double x); private static double F1(double a, double x) { return a * x * x; } private static double F2(double a, double x) { return a * Math.Sin(x); } public static void SaveFunc(string fileName, double a, double b, double h, int func) { // используя делегат выбираем нужную функцию и дальше ее используем (строка 48) Function del; if (func == 1) { del = F1; } else { del = F2; } FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); BinaryWriter bw = new BinaryWriter(fs); double x = a; while (x <= b) { bw.Write(del.Invoke(a, x)); x += h; } bw.Close(); fs.Close(); } public static double Load(string fileName) { FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); BinaryReader bw = new BinaryReader(fs); double min = double.MaxValue; double d; for (int i = 0; i < fs.Length / sizeof(double); i++) { // Считываем значение и переходим к следующему d = bw.ReadDouble(); if (d < min) min = d; } bw.Close(); fs.Close(); return min; } public static int[] Menu() { int[] variables = new int[3]; Console.Write("Выберите функцию: 1 - a*x^2; другое число - a*sin(x): "); variables[0] = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("На каком отрезке функции находить минимум?\n" + "Введите начальное значение X и конечное.\n" + "При этом a = начальному значению отрезка: "); variables[1] = Convert.ToInt32(Console.ReadLine()); variables[2] = Convert.ToInt32(Console.ReadLine()); return variables; } static void Main(string[] args) { int[] variables = Menu(); SaveFunc("data.bin", variables[1], variables[2], 0.5, variables[0]); Console.WriteLine(Load("data.bin")); Console.ReadKey(); } } } |