Вывод отрицательного числа в Н-ой системе счисления
Как сделать операции над отрицательными числами систем счисления? Необходимо реализовать вывод отрицательного числа. Нет идей как сделать.
Программа работает с различными СС, при отрицательной системе выводит ошибочный результат.
Вот код всей программы
private void button3_Click(object sender, EventArgs e)
{
char[] numb = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
string firstStr = first_num.Text;
string twoStr = two_num.Text;
int firstDegreeInput, twoDegreeInput, resultDegreeOutput;
// Условие равно ли число просто -, без числа
if (firstStr == "-" ||
twoStr == "-")
{
MessageBox.Show("Число содержит недопустимые символы!");
return;
}
// Проверка на заполненность строк
if (firstStr != "" && // Первое число
twoStr != "" && // Второе число
first_degree.Text != "" && // СС первого числа
two_degree.Text != "" && // СС второго числа
arithmetic_select.Text != "" && // Арифметические операции
result_degree.Text != "") // СС результата (выбирает пользователь)
{
// Конвертация строк выбора СС из строкового типа в целочисленный
firstDegreeInput = Convert.ToInt32(first_degree.Text);
twoDegreeInput = Convert.ToInt32(two_degree.Text);
resultDegreeOutput = Convert.ToInt32(result_degree.Text);
// Цикл проверки первого числа на СС
for (int i = 0; i < firstStr.Length; i++)
{
for (int j = 0; j < 20; j++)
{
if (firstStr[i] == numb[j])
{
if (j > (firstDegreeInput - 1))
{
MessageBox.Show("Первое число не соответствует системе счисления.");
return;
}
}
}
}
// Цикл проверки второе числа на СС
for (int i = 0; i < twoStr.Length; i++)
{
for (int j = 0; j < 20; j++)
{
if (twoStr[i] == numb[j])
{
if (j > (twoDegreeInput - 1))
{
MessageBox.Show("Второе число не соответствует системе счисления.");
return;
}
}
}
}
}
else
{
MessageBox.Show("Заполните все поля!");
return;
}
// Перевод числа в десятичную степень
int numTen1 = 0;
int numTen2 = 0;
int degree1 = 0;
int degree2 = 0;
for (int i = firstStr.Length - 1; i >= 0; i--)
{
for (int j = 0; j < 20; j++)
{
if (firstStr[i] == numb[j])
{
numTen1 += (int)(j * Math.Pow(firstDegreeInput, degree1));
degree1++;
break;
}
}
}
for (int i = twoStr.Length - 1; i >= 0; i--)
{
for (int j = 0; j < 20; j++)
{
if (twoStr[i] == numb[j])
{
numTen2 += (int)(j * Math.Pow(twoDegreeInput, degree2));
degree2++;
break;
}
}
}
// Арифметические операции
int numTenMain = 0;
if (arithmetic_select.Text == "+")
{
numTenMain = numTen1 + numTen2;
}
else if (arithmetic_select.Text == "-")
{
numTenMain = numTen1 - numTen2;
}
else if (arithmetic_select.Text == "*")
{
numTenMain = numTen1 * numTen2;
}
else if (arithmetic_select.Text == "/")
{
numTenMain = numTen1 / numTen2;
};
// Вывод результата
string result = "";
while (numTenMain != 0)
{
result = numb[numTenMain % resultDegreeOutput].ToString() + result;
numTenMain /= resultDegreeOutput;
}
result_str.Text = result;
}
