Sybatron

SADITO RIGHT CODE

Dec 25th, 2018
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.04 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ConsoleApplication1
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             int[] NegClosest = new int[2], PosClosest = new int[2];
  13.             NegClosest[0] = int.MinValue;
  14.             PosClosest[0] = int.MaxValue;
  15.             Console.Write("Въведете големината на едномерен масив:");
  16.             int n = int.Parse(Console.ReadLine());
  17.             Console.Write("Въведете число, с което ще сравнявате:");
  18.             int num = int.Parse(Console.ReadLine());
  19.  
  20.             int[] a = new int[n];
  21.             Console.WriteLine("Въведете числата:");
  22.             for (int i = 0; i < n; i++)
  23.             {
  24.                 a[i] = int.Parse(Console.ReadLine());
  25.                 if (num - a[i] >= 0 && PosClosest[0] > num - a[i])
  26.                 {
  27.                     PosClosest[0] = num - a[i];
  28.                     PosClosest[1] = a[i];
  29.                 }
  30.                 else if (num - a[i] <= 0 && NegClosest[0] < num - a[i])
  31.                 {
  32.                     NegClosest[0] = num - a[i];
  33.                     NegClosest[1] = a[i];
  34.                 }
  35.             }
  36.             int closest;
  37.             string pos = "";
  38.             try
  39.             {
  40.                 if (Math.Abs(NegClosest[0]) < PosClosest[0])
  41.                 {
  42.                     closest = NegClosest[1];
  43.                 }
  44.                 else closest = PosClosest[1];
  45.             }
  46.             catch (Exception)
  47.             {
  48.                 closest = PosClosest[1];
  49.             }
  50.             for (int i = 0; i < n; i++)
  51.             {
  52.                 if (closest == a[i])
  53.                 {
  54.                     pos += (i+1) + " | ";
  55.                 }
  56.             }
  57.             Console.WriteLine("Най-близкото число до {0} е {1}.", num, closest);
  58.             Console.WriteLine("Намира се на позиции " + pos);
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment