Top.Mail.Ru

Windows Form C#. - вопрос №5646786

Проблема за проблемой. Делаю калькулятор, но использую самые базовые и простейшие команды, т.к. на любимой учёбе мы не проходили это. Беру пример со встроенного в Windows 10 калькулятор. Когда запускаешь (и не только запускаешь, например стираешь) калькулятор появляется 0 в строке, правильно. Этот ноль у меня есть, всё работает. Но стоит мне нажать на минус, плюс, умножение и деление на моём калькуляторе, они не появляются вообще. Ваша задача: сделать так, чтобы они появились справа от нуля. То есть, я нажимаю на минус появляется минус, нажимаю на плюс и минус должен замениться на плюс. Нажимаю на умножение и плюс должен замениться на умножение, понимаете логику? И желательно с объяснениями. без setOperation, try, catch (FormatException), switch (option), case, break, default, return. Соответственно, все математические операции на этих кнопках тоже должны работать. Вот код:

namespace threeone
{
public partial class Form1: Form
{
public Form1()
{
InitializeComponent();
}


private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == «0»)
{
textBox1.Text = "";
}
if (textBox1.Text == «00»)
{
textBox1.Text = "";
}
textBox1.Text += (sender as Button).Text; // Обращение к тексту кнопки
}
int m;
int minus;
int umnoz;
int delenie;
int operation;
private void button18_Click(object sender, EventArgs e)
{
m = Convert.ToInt32(textBox1.Text); // Запомнили число
textBox1.Text += "+"; //
operation = '+';
}
private void button17_Click(object sender, EventArgs e)
{
umnoz = Convert.ToInt32(textBox1.Text); // Запомнили число
textBox1.Text += "*"; //
operation = '*';
}
private void button19_Click(object sender, EventArgs e)
{
minus = Convert.ToInt32(textBox1.Text); // Запомнили число
textBox1.Text += "-"; //
operation = '-';
}
private void button13_Click(object sender, EventArgs e)
{
delenie = Convert.ToInt32(textBox1.Text); // Запомнили число
textBox1.Text += "/"; //
operation = '/';
}
private void button16_Click(object sender, EventArgs e)
{
if (operation == '+')
{
textBox1.Text = (m + Convert.ToInt32(textBox1.Text)).ToString();
}
if (operation == '-')
{
textBox1.Text = (minus — Convert.ToInt32(textBox1.Text)).ToString();
}
if (operation == 'x')
{
textBox1.Text = (umnoz * Convert.ToInt32(textBox1.Text)).ToString();
}
if (operation == '/')
{
textBox1.Text = (delenie / Convert.ToInt32(textBox1.Text)).ToString();
}
}

C#

Ответы

Вот примерно так должно быть:

 

using System;
using System.Windows.Forms;

namespace threeone
{
public partial class Form1: Form
{
private double firstNumber = 0;
private string currentOperation = "";
private bool isNewNumberStarting = true;

public Form1()
{
InitializeComponent();
}

private void NumberButton_Click(object sender, EventArgs e)
{
string buttonText = (sender as Button).Text;

if (isNewNumberStarting)
{
textBox1.Text = "";
isNewNumberStarting = false;
}

if (!(textBox1.Text == «0» && buttonText == «0»))
{
if (textBox1.Text == «0»)
{
textBox1.Text = buttonText;
}
else
{
textBox1.Text += buttonText;
}
}
}

private void OperationButton_Click(object sender, EventArgs e)
{
firstNumber = Convert.ToDouble(textBox1.Text);
currentOperation = (sender as Button).Text;
isNewNumberStarting = true;
textBox1.Text += currentOperation;
}

private void EqualsButton_Click(object sender, EventArgs e)
{
string displayText = textBox1.Text;
int operationIndex = displayText.LastIndexOfAny(new char[] { '+', '-', '*', '/' });

double secondNumber = Convert.ToDouble(displayText.Substring(operationIndex + 1));

double result = 0;
switch (currentOperation)
{
case "+":
result = firstNumber + secondNumber;
break;
case "-":
result = firstNumber — secondNumber;
break;
case "*":
result = firstNumber * secondNumber;
break;
case "/":
result = firstNumber / secondNumber;
break;
}

textBox1.Text = result.ToString();
isNewNumberStarting = true;
currentOperation = "";
}
}
}

03.02.25

Виталий

Читать ответы
Посмотреть всех экспертов из раздела Технологии > C/C++
Пользуйтесь нашим приложением Доступно на Google Play Загрузите в App Store