Browse Source

калькулятор работает, но нет валидации и не считает отрицательные числа

Алёна Плотникова 3 năm trước cách đây
mục cha
commit
5e2415cdc2
2 tập tin đã thay đổi với 235 bổ sung34 xóa
  1. 68 34
      numbersystem/MainWindow.xaml
  2. 167 0
      numbersystem/MainWindow.xaml.cs

+ 68 - 34
numbersystem/MainWindow.xaml

@@ -8,9 +8,17 @@
         Title="Система счислений" Height="550" Width="350" ResizeMode="NoResize" Icon="/icon.png" FontFamily="Montserrat Light">
     <Window.Resources>
         <Style TargetType="Button">
-            <Setter Property="ItemsControl.Background" Value="#8888d7"/>
-            <Setter Property="ItemsControl.Foreground" Value="White"/>
-            <Setter Property="ItemsControl.Margin" Value="10"/>
+            <Style.Setters>
+                <Setter Property="ItemsControl.Background" Value="#8888d7"/>
+                <Setter Property="ItemsControl.Foreground" Value="White"/>
+                <Setter Property="ItemsControl.Margin" Value="10"/>
+            </Style.Setters>
+            <Style.Triggers>
+                <Trigger Property="IsMouseOver" Value="True">
+                    <Setter Property="Background" Value="White" />
+                    <Setter Property="Foreground" Value="Black" />
+                </Trigger>
+            </Style.Triggers>
         </Style>
     </Window.Resources>
     <Grid>
@@ -33,40 +41,66 @@
                         <ColumnDefinition/>
                         <ColumnDefinition/>
                     </Grid.ColumnDefinitions>
-                    <TextBox IsReadOnly="True" Grid.Row="0" Grid.ColumnSpan="4" Margin="10" 
+                    <TextBox x:Name="str" IsReadOnly="True" Grid.Row="0" Grid.ColumnSpan="4" Margin="10" 
                              FontSize="16" HorizontalScrollBarVisibility="Auto" 
-                             VerticalContentAlignment="Center" HorizontalContentAlignment="Right"/>
+                             VerticalContentAlignment="Center" HorizontalContentAlignment="Right"
+                             PreviewTextInput="str_PreviewTextInput"
+                             KeyDown="str_KeyDown" PreviewKeyDown="str_KeyDown"/>
                     <Label Content="Выберите СС:" Grid.Row="1" Grid.ColumnSpan="2" Margin="10,10,43,10" FontSize="14"/>
-                    <ComboBox Margin="48,10,10,30" Grid.ColumnSpan="3" Grid.Column="1" Grid.Row="1">
-                        <TextBlock Text="Двоичная"/>
-                        <TextBlock Text="Троичная"/>
-                        <TextBlock Text="Восьмеричная"/>
-                        <TextBlock Text="Шестнадцатиричная"/>
+                    <ComboBox x:Name="comboBox" Margin="48,10,10,30" Grid.ColumnSpan="3" Grid.Column="1" Grid.Row="1" 
+                              SelectionChanged="ComboBox_SelectionChanged">
+                        <ComboBoxItem Content="Двоичная"/>
+                        <ComboBoxItem Content="Восьмеричная"/>
+                        <ComboBoxItem Content="Шестнадцатиричная"/>
                     </ComboBox>
-                    <Button Content="CA" Grid.Row="5" Grid.Column="0"/>
-                    <Button Content="0" Grid.Row="5" Grid.Column="1"/>
-                    <Button Content="⌫" Grid.Row="5" Grid.Column="2"/>
-                    <Button Content="1" Grid.Row="4" Grid.Column="0"/>
-                    <Button Content="2" Grid.Row="4" Grid.Column="1"/>
-                    <Button Content="3" Grid.Row="4" Grid.Column="2"/>
-                    <Button Content="4" Grid.Row="3" Grid.Column="0"/>
-                    <Button Content="5" Grid.Row="3" Grid.Column="1"/>
-                    <Button Content="6" Grid.Row="3" Grid.Column="2"/>
-                    <Button Content="7" Grid.Row="2" Grid.Column="0"/>
-                    <Button Content="8" Grid.Row="2" Grid.Column="1"/>
-                    <Button Content="9" Grid.Row="2" Grid.Column="2"/>
-                    <Button Content="A" Grid.Row="6" Grid.Column="0" Background="#6c6cdf"/>
-                    <Button Content="B" Grid.Row="6" Grid.Column="1" Background="#6c6cdf"/>
-                    <Button Content="C" Grid.Row="6" Grid.Column="2" Background="#6c6cdf"/>
-                    <Button Content="D" Grid.Row="7" Grid.Column="0" Background="#6c6cdf"/>
-                    <Button Content="E" Grid.Row="7" Grid.Column="1" Background="#6c6cdf"/>
-                    <Button Content="F" Grid.Row="7" Grid.Column="2" Background="#6c6cdf"/>
-                    <Button Content="+" Grid.Row="2" Grid.Column="3" Background="#4040bf"/>
-                    <Button Content="-" Grid.Row="3" Grid.Column="3" Background="#4040bf"/>
-                    <Button Content="×" Grid.Row="4" Grid.Column="3" Background="#4040bf"/>
-                    <Button Content="÷" Grid.Row="5" Grid.Column="3" Background="#4040bf"/>
-                    <Button Content="%" Grid.Row="6" Grid.Column="3" Background="#4040bf"/>
-                    <Button Content="=" Grid.Row="7" Grid.Column="3" Background="#4040bf"/>
+                    <Button x:Name="ca" 
+                            Content="CA" Grid.Row="5" Grid.Column="0"/>
+                    <Button x:Name="zero" 
+                            Content="0" Grid.Row="5" Grid.Column="1"/>
+                    <Button x:Name="erase" 
+                            Content="⌫" Grid.Row="5" Grid.Column="2"/>
+                    <Button x:Name="one" 
+                            Content="1" Grid.Row="4" Grid.Column="0"/>
+                    <Button x:Name="two" 
+                            Content="2" Grid.Row="4" Grid.Column="1"/>
+                    <Button x:Name="three" 
+                            Content="3" Grid.Row="4" Grid.Column="2"/>
+                    <Button x:Name="four" 
+                            Content="4" Grid.Row="3" Grid.Column="0"/>
+                    <Button x:Name="five" 
+                            Content="5" Grid.Row="3" Grid.Column="1"/>
+                    <Button x:Name="six" 
+                            Content="6" Grid.Row="3" Grid.Column="2"/>
+                    <Button x:Name="seven" 
+                            Content="7" Grid.Row="2" Grid.Column="0"/>
+                    <Button x:Name="eight" 
+                            Content="8" Grid.Row="2" Grid.Column="1"/>
+                    <Button x:Name="nine" 
+                            Content="9" Grid.Row="2" Grid.Column="2"/>
+                    <Button x:Name="a" 
+                            Content="A" Grid.Row="6" Grid.Column="0" Background="#6c6cdf"/>
+                    <Button x:Name="b" 
+                            Content="B" Grid.Row="6" Grid.Column="1" Background="#6c6cdf"/>
+                    <Button x:Name="c" 
+                            Content="C" Grid.Row="6" Grid.Column="2" Background="#6c6cdf"/>
+                    <Button x:Name="d" 
+                            Content="D" Grid.Row="7" Grid.Column="0" Background="#6c6cdf"/>
+                    <Button x:Name="e" 
+                            Content="E" Grid.Row="7" Grid.Column="1" Background="#6c6cdf"/>
+                    <Button x:Name="f" 
+                            Content="F" Grid.Row="7" Grid.Column="2" Background="#6c6cdf"/>
+                    <Button x:Name="plus" 
+                            Content="+" Grid.Row="2" Grid.Column="3" Background="#4040bf"/>
+                    <Button x:Name="minus" 
+                            Content="-" Grid.Row="3" Grid.Column="3" Background="#4040bf"/>
+                    <Button x:Name="multiply" 
+                            Content="×" Grid.Row="4" Grid.Column="3" Background="#4040bf"/>
+                    <Button x:Name="division" 
+                            Content="÷" Grid.Row="5" Grid.Column="3" Background="#4040bf"/>
+                    <Button x:Name="remains" 
+                            Content="%" Grid.Row="6" Grid.Column="3" Background="#4040bf"/>
+                    <Button x:Name="equal" 
+                            Content="=" Grid.Row="7" Grid.Column="3" Background="#4040bf"/>
                 </Grid>
             </TabItem>
             <TabItem Header="История" FontFamily="Montserrat Light">

+ 167 - 0
numbersystem/MainWindow.xaml.cs

@@ -23,6 +23,173 @@ namespace numbersystem
         public MainWindow()
         {
             InitializeComponent();
+            str.Focus();
         }
+
+        // выбор системы счисления
+        int ss = 0;
+        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
+        {
+            ComboBox comboBox = (ComboBox)sender;
+            ComboBoxItem selectedItem = (ComboBoxItem)comboBox.SelectedItem;
+
+            if (Convert.ToString(selectedItem.Content) == "Двоичная")
+                ss = 2;
+            else if (Convert.ToString(selectedItem.Content) == "Восьмеричная")
+                ss = 8;
+            else if (Convert.ToString(selectedItem.Content) == "Шестнадцатиричная")
+                ss = 16;
+
+            str.Focus();
+        }
+
+        string expression; // переменная для выражения
+        int res; // переменная для результата
+
+        // ввод цифр, букв и знаков операций
+        private void str_PreviewTextInput(object sender, TextCompositionEventArgs e)
+        {
+            // при нажатии на цифры или буквы
+            if(Int32.TryParse(e.Text, out int n) 
+                || e.Text == "a" || e.Text == "b" || e.Text == "c" || e.Text == "d" || e.Text == "e" || e.Text == "f")
+            {
+                str.Text += e.Text;
+            }
+
+            // при нажатии на знаки операций
+            if(e.Text == "+" || e.Text == "-" || e.Text == "/" || e.Text == "*" || e.Text == "%")
+            {
+                str.Text += " ";
+                str.Text += e.Text;
+                str.Text += " ";
+            }
+
+            // при нажатии на "равно"
+            if(e.Text == "=")
+            {
+                if(ss == 0)
+                {
+                    MessageBox.Show("Не выбрана система счисления");
+                    return;
+                }
+
+                // записываем выражение в переменную
+                expression = str.Text;
+
+                // разбиваем строку на массив
+                string[] arr = expression.Split(' ');
+
+                // перебираем массив и считаем высокоприоритетные операции
+                for (int i = 0; i < arr.Length; i++)
+                {
+                    // умножение
+                    if(arr[i] == "*")
+                    {
+                        if(arr[i - 1] == "_")
+                        {
+                            arr[i] = Convert.ToString(Convert.ToInt32(arr[i - 2], ss) * Convert.ToInt32(arr[i + 1], ss), ss);
+                            arr[i - 2] = "_";
+                            arr[i + 1] = "_";
+                        }
+                        else
+                        {
+                            arr[i] = Convert.ToString(Convert.ToInt32(arr[i - 1], ss) * Convert.ToInt32(arr[i + 1], ss), ss);
+                            arr[i - 1] = "_";
+                            arr[i + 1] = "_";
+                        }
+                    }
+                    // деление
+                    else if(arr[i] == "/")
+                    {
+                        if (arr[i - 1] == "_")
+                        {
+                            arr[i] = Convert.ToString(Convert.ToInt32(arr[i - 2], ss) / Convert.ToInt32(arr[i + 1], ss), ss);
+                            arr[i - 2] = "_";
+                            arr[i + 1] = "_";
+                        }
+                        else
+                        {
+                            arr[i] = Convert.ToString(Convert.ToInt32(arr[i - 1], ss) / Convert.ToInt32(arr[i + 1], ss), ss);
+                            arr[i - 1] = "_";
+                            arr[i + 1] = "_";
+                        }
+                    }
+                    // остаток от деления
+                    else if(arr[i] == "%")
+                    {
+                        if (arr[i - 1] == "_")
+                        {
+                            arr[i] = Convert.ToString(Convert.ToInt32(arr[i - 2], ss) % Convert.ToInt32(arr[i + 1], ss), ss);
+                            arr[i - 2] = "_";
+                            arr[i + 1] = "_";
+                        }
+                        else
+                        {
+                            arr[i] = Convert.ToString(Convert.ToInt32(arr[i - 1], ss) % Convert.ToInt32(arr[i + 1], ss), ss);
+                            arr[i - 1] = "_";
+                            arr[i + 1] = "_";
+                        }
+                    }
+                }
+
+                // узнаем размер будущего массива
+                int l = 0;
+                for (int i = 0; i < arr.Length; i++)
+                {
+                    if (arr[i] != "_")
+                    {
+                        l++;
+                    }
+                }
+
+                // записать в новый массив результат предыдущего шага
+                string[] arr2 = new string[l];
+                int j = 0;
+                for (int i = 0; i < arr.Length; i++)
+                {
+                    if (arr[i] != "_")
+                    {
+                        arr2[j] = arr[i];
+                        j++;
+                    }
+                }
+
+                // первое число массива присваиваем переменной
+                res = Convert.ToInt32(arr2[0], ss);
+
+                // перебираем массив и считаем остальные операции
+                for (int i = 1; i < arr2.Length; i++)
+                {
+                    // сложение
+                    if (arr2[i] == "+")
+                    {
+                        res += Convert.ToInt32(arr2[i + 1], ss);
+                    }
+                    // вычитание
+                    else if (arr2[i] == "-")
+                    {
+                        res -= Convert.ToInt32(arr2[i + 1], ss);
+                    }
+                }
+
+                // выводим результат
+                str.Text = Convert.ToString(res, ss);
+            }
+        }
+
+        // кнопки стереть
+        private void str_KeyDown(object sender, KeyEventArgs e)
+        {
+            if(e.Key == Key.Delete)
+            {
+                str.Text = "";
+            }
+            if(e.Key == Key.Back)
+            {
+                if(str.Text.Length > 0)
+                str.Text = str.Text.Substring(0, str.Text.Length - 1);
+            }
+        }
+
     }
 }