Кнопочный калькулятор с textBox
Рассмотрим все поэтапно.
Для начала нужно добавить в форму кнопки Button
, один label
и три textBox
.
В свойствах каждой кнопки меняем названия на 1, 2, ..., 9, "+", "-"
и т.д.
Двойным щелчком по любой из кнопок переходим к коду.
1. Выведем в textBox
цифру по нажатию на Button
.
В код кнопки Button1
добавляем:
textBox1->Text += "1"; //Теперь по нажатию на Button1 в textBox добавляется 1.
Остальные кнопки с цифрами делаем аналогично.
2. Знаки будем выводить в label1
.
В код кнопки Button11
добавляем:
label1->Text = "+"; //Т.е. по нажатию на Button11 меняем знак в label1 на "+"
Аналогично добавляем остальные знаки.
3. Если заполнены textBox1
и label1
, пора заполнять textBox2
. Для этого можно использовать условие if
.
Т.е. в коде каждого из textBox
надо написать, к примеру:
if(label1->Text == "") textBox1->Text += "1";
else textBox2->Text += "1";
Так мы попадем в textBox2
. В свойствах название label1
нужно стереть и нажать на Enter! А то не сработает.
4. Вычисляем значение и записываем его в textBox3
.
В коде кнопки "=" напишем:
double b;
switch(label1->Text[0])
{
case '+':
b = Convert::ToDouble(textBox1->Text) + Convert::ToDouble(textBox2->Text);
break;
case '-':
b = Convert::ToDouble(textBox1->Text) - Convert::ToDouble(textBox2->Text);
break;
case '*':
b = Convert::ToDouble(textBox1->Text) * Convert::ToDouble(textBox2->Text);
break;
case '/':
b = Convert::ToDouble(textBox1->Text) / Convert::ToDouble(textBox2->Text);
break;
}
textBox3->Text = Convert::ToString(b); //вывод результата в textBox3
Т.е. производим вычисления с числами, находящимися в textBox1
и textBox2
, со знаком, взятым из label1
.
Convert
используется для перевода строки из одного типа в другой.
5. Запись дробного числа.
Поставить запятую труда не составит:
textBox1->Text += ",";
Фишка в том, что надо ограничить пользователя в постановке запятых.
if(!textBox1->Text->Contains(",")) textBox1->Text += ",";
//Contains проверит, нет ли в строке запятых
Мы рассмотрели основные моменты для написания калькулятора. На этой основе Вы можете сами написать калькулятор своей мечты ;)
Вот код готового калькулятора, включаещего в себя дополнительные функции, а так же вычисление числовыми цепями.
Для запуска вставьте этот код и вместо Project1 напишите название своего проекта!!!
#pragma once
namespace Project1 {
double a, b, save; //по нажатию на MS число из textBox1 сохраняется в save
bool con = true; //после нажатия "=" con меняется на false и по нажатию на цифру происходит очистка и ввод новых данных в textBox1
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
///
/// Сводка для MyForm
///
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: добавьте код конструктора
//
}
protected:
///
/// Освободить все используемые ресурсы.
///
~MyForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ button1;
protected:
private: System::Windows::Forms::Button^ button2;
private: System::Windows::Forms::Button^ button3;
private: System::Windows::Forms::Button^ button4;
private: System::Windows::Forms::Button^ button5;
private: System::Windows::Forms::Button^ button6;
private: System::Windows::Forms::Button^ button7;
private: System::Windows::Forms::Button^ button8;
private: System::Windows::Forms::Button^ button9;
private: System::Windows::Forms::TextBox^ textBox1;
private: System::Windows::Forms::Button^ button10;
private: System::Windows::Forms::Button^ button11;
private: System::Windows::Forms::Button^ button12;
private: System::Windows::Forms::Button^ button13;
private: System::Windows::Forms::Button^ button14;
private: System::Windows::Forms::Button^ button15;
private: System::Windows::Forms::Button^ button16;
private: System::Windows::Forms::Button^ button17;
private: System::Windows::Forms::Button^ button18;
private: System::Windows::Forms::Button^ button19;
private: System::Windows::Forms::Button^ button20;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Button^ button21;
private: System::Windows::Forms::Button^ button22;
private: System::Windows::Forms::Label^ label2;
private:
///
/// Требуется переменная конструктора.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Обязательный метод для поддержки конструктора - не изменяйте
/// содержимое данного метода при помощи редактора кода.
///
void InitializeComponent(void)
{
this->button1 = (gcnew System::Windows::Forms::Button());
this->button2 = (gcnew System::Windows::Forms::Button());
this->button3 = (gcnew System::Windows::Forms::Button());
this->button4 = (gcnew System::Windows::Forms::Button());
this->button5 = (gcnew System::Windows::Forms::Button());
this->button6 = (gcnew System::Windows::Forms::Button());
this->button7 = (gcnew System::Windows::Forms::Button());
this->button8 = (gcnew System::Windows::Forms::Button());
this->button9 = (gcnew System::Windows::Forms::Button());
this->textBox1 = (gcnew System::Windows::Forms::TextBox());
this->button10 = (gcnew System::Windows::Forms::Button());
this->button11 = (gcnew System::Windows::Forms::Button());
this->button12 = (gcnew System::Windows::Forms::Button());
this->button13 = (gcnew System::Windows::Forms::Button());
this->button14 = (gcnew System::Windows::Forms::Button());
this->button15 = (gcnew System::Windows::Forms::Button());
this->button16 = (gcnew System::Windows::Forms::Button());
this->button17 = (gcnew System::Windows::Forms::Button());
this->button18 = (gcnew System::Windows::Forms::Button());
this->button19 = (gcnew System::Windows::Forms::Button());
this->button20 = (gcnew System::Windows::Forms::Button());
this->label1 = (gcnew System::Windows::Forms::Label());
this->button21 = (gcnew System::Windows::Forms::Button());
this->button22 = (gcnew System::Windows::Forms::Button());
this->label2 = (gcnew System::Windows::Forms::Label());
this->SuspendLayout();
//
// button1
//
this->button1->Location = System::Drawing::Point(12, 66);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(75, 23);
this->button1->TabIndex = 0;
this->button1->Text = L"1";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click);
//
// button2
//
this->button2->Location = System::Drawing::Point(93, 66);
this->button2->Name = L"button2";
this->button2->Size = System::Drawing::Size(75, 23);
this->button2->TabIndex = 1;
this->button2->Text = L"2";
this->button2->UseVisualStyleBackColor = true;
this->button2->Click += gcnew System::EventHandler(this, &MyForm::button2_Click);
//
// button3
//
this->button3->Location = System::Drawing::Point(174, 38);
this->button3->Name = L"button3";
this->button3->Size = System::Drawing::Size(75, 23);
this->button3->TabIndex = 2;
this->button3->Text = L"3";
this->button3->UseVisualStyleBackColor = true;
this->button3->Click += gcnew System::EventHandler(this, &MyForm::button3_Click);
//
// button4
//
this->button4->Location = System::Drawing::Point(12, 95);
this->button4->Name = L"button4";
this->button4->Size = System::Drawing::Size(75, 23);
this->button4->TabIndex = 3;
this->button4->Text = L"4";
this->button4->UseVisualStyleBackColor = true;
this->button4->Click += gcnew System::EventHandler(this, &MyForm::button4_Click);
//
// button5
//
this->button5->Location = System::Drawing::Point(94, 95);
this->button5->Name = L"button5";
this->button5->Size = System::Drawing::Size(75, 23);
this->button5->TabIndex = 4;
this->button5->Text = L"5";
this->button5->UseVisualStyleBackColor = true;
this->button5->Click += gcnew System::EventHandler(this, &MyForm::button5_Click);
//
// button6
//
this->button6->Location = System::Drawing::Point(174, 67);
this->button6->Name = L"button6";
this->button6->Size = System::Drawing::Size(75, 23);
this->button6->TabIndex = 5;
this->button6->Text = L"6";
this->button6->UseVisualStyleBackColor = true;
this->button6->Click += gcnew System::EventHandler(this, &MyForm::button6_Click);
//
// button7
//
this->button7->Location = System::Drawing::Point(12, 125);
this->button7->Name = L"button7";
this->button7->Size = System::Drawing::Size(75, 23);
this->button7->TabIndex = 6;
this->button7->Text = L"7";
this->button7->UseVisualStyleBackColor = true;
this->button7->Click += gcnew System::EventHandler(this, &MyForm::button7_Click);
//
// button8
//
this->button8->Location = System::Drawing::Point(94, 125);
this->button8->Name = L"button8";
this->button8->Size = System::Drawing::Size(75, 23);
this->button8->TabIndex = 7;
this->button8->Text = L"8";
this->button8->UseVisualStyleBackColor = true;
this->button8->Click += gcnew System::EventHandler(this, &MyForm::button8_Click);
//
// button9
//
this->button9->Location = System::Drawing::Point(175, 96);
this->button9->Name = L"button9";
this->button9->Size = System::Drawing::Size(75, 23);
this->button9->TabIndex = 8;
this->button9->Text = L"9";
this->button9->UseVisualStyleBackColor = true;
this->button9->Click += gcnew System::EventHandler(this, &MyForm::button9_Click);
//
// textBox1
//
this->textBox1->Location = System::Drawing::Point(12, 12);
this->textBox1->Name = L"textBox1";
this->textBox1->Size = System::Drawing::Size(314, 20);
this->textBox1->TabIndex = 9;
//
// button10
//
this->button10->Location = System::Drawing::Point(256, 38);
this->button10->Name = L"button10";
this->button10->Size = System::Drawing::Size(75, 23);
this->button10->TabIndex = 10;
this->button10->Text = L"+";
this->button10->UseVisualStyleBackColor = true;
this->button10->Click += gcnew System::EventHandler(this, &MyForm::button10_Click);
//
// button11
//
this->button11->Location = System::Drawing::Point(256, 67);
this->button11->Name = L"button11";
this->button11->Size = System::Drawing::Size(75, 23);
this->button11->TabIndex = 11;
this->button11->Text = L"-";
this->button11->UseVisualStyleBackColor = true;
this->button11->Click += gcnew System::EventHandler(this, &MyForm::button11_Click);
//
// button12
//
this->button12->Location = System::Drawing::Point(256, 96);
this->button12->Name = L"button12";
this->button12->Size = System::Drawing::Size(75, 23);
this->button12->TabIndex = 12;
this->button12->Text = L"*";
this->button12->UseVisualStyleBackColor = true;
this->button12->Click += gcnew System::EventHandler(this, &MyForm::button12_Click);
//
// button13
//
this->button13->Location = System::Drawing::Point(93, 37);
this->button13->Name = L"button13";
this->button13->Size = System::Drawing::Size(75, 23);
this->button13->TabIndex = 13;
this->button13->Text = L"0";
this->button13->UseVisualStyleBackColor = true;
this->button13->Click += gcnew System::EventHandler(this, &MyForm::button13_Click);
//
// button14
//
this->button14->Location = System::Drawing::Point(12, 38);
this->button14->Name = L"button14";
this->button14->Size = System::Drawing::Size(38, 23);
this->button14->TabIndex = 14;
this->button14->Text = L".";
this->button14->UseVisualStyleBackColor = true;
this->button14->Click += gcnew System::EventHandler(this, &MyForm::button14_Click);
//
// button15
//
this->button15->Location = System::Drawing::Point(174, 125);
this->button15->Name = L"button15";
this->button15->Size = System::Drawing::Size(75, 23);
this->button15->TabIndex = 15;
this->button15->Text = L"C";
this->button15->UseVisualStyleBackColor = true;
this->button15->Click += gcnew System::EventHandler(this, &MyForm::button15_Click);
//
// button16
//
this->button16->Location = System::Drawing::Point(255, 125);
this->button16->Name = L"button16";
this->button16->Size = System::Drawing::Size(75, 23);
this->button16->TabIndex = 16;
this->button16->Text = L"/";
this->button16->UseVisualStyleBackColor = true;
this->button16->Click += gcnew System::EventHandler(this, &MyForm::button16_Click);
//
// button17
//
this->button17->Location = System::Drawing::Point(255, 155);
this->button17->Name = L"button17";
this->button17->Size = System::Drawing::Size(75, 23);
this->button17->TabIndex = 17;
this->button17->Text = L"=";
this->button17->UseVisualStyleBackColor = true;
this->button17->Click += gcnew System::EventHandler(this, &MyForm::button17_Click);
//
// button18
//
this->button18->Location = System::Drawing::Point(12, 154);
this->button18->Name = L"button18";
this->button18->Size = System::Drawing::Size(61, 23);
this->button18->TabIndex = 18;
this->button18->Text = L"MS";
this->button18->UseVisualStyleBackColor = true;
this->button18->Click += gcnew System::EventHandler(this, &MyForm::button18_Click);
//
// button19
//
this->button19->Location = System::Drawing::Point(79, 154);
this->button19->Name = L"button19";
this->button19->Size = System::Drawing::Size(59, 23);
this->button19->TabIndex = 19;
this->button19->Text = L"MR";
this->button19->UseVisualStyleBackColor = true;
this->button19->Click += gcnew System::EventHandler(this, &MyForm::button19_Click);
//
// button20
//
this->button20->Location = System::Drawing::Point(144, 155);
this->button20->Name = L"button20";
this->button20->Size = System::Drawing::Size(53, 23);
this->button20->TabIndex = 20;
this->button20->Text = L"MC";
this->button20->UseVisualStyleBackColor = true;
this->button20->Click += gcnew System::EventHandler(this, &MyForm::button20_Click);
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(306, 15);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(0, 13);
this->label1->TabIndex = 23;
//
// button21
//
this->button21->Location = System::Drawing::Point(49, 38);
this->button21->Name = L"button21";
this->button21->Size = System::Drawing::Size(38, 23);
this->button21->TabIndex = 24;
this->button21->Text = L"-";
this->button21->UseVisualStyleBackColor = true;
this->button21->Click += gcnew System::EventHandler(this, &MyForm::button21_Click);
//
// button22
//
this->button22->Location = System::Drawing::Point(203, 155);
this->button22->Name = L"button22";
this->button22->Size = System::Drawing::Size(46, 23);
this->button22->TabIndex = 25;
this->button22->Text = L"CE";
this->button22->UseVisualStyleBackColor = true;
this->button22->Click += gcnew System::EventHandler(this, &MyForm::button22_Click);
//
// label2
//
this->label2->AutoSize = true;
this->label2->Location = System::Drawing::Point(270, 15);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(0, 13);
this->label2->TabIndex = 26;
//
// MyForm
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(338, 183);
this->Controls->Add(this->label2);
this->Controls->Add(this->button22);
this->Controls->Add(this->button21);
this->Controls->Add(this->label1);
this->Controls->Add(this->button20);
this->Controls->Add(this->button19);
this->Controls->Add(this->button18);
this->Controls->Add(this->button17);
this->Controls->Add(this->button16);
this->Controls->Add(this->button15);
this->Controls->Add(this->button14);
this->Controls->Add(this->button13);
this->Controls->Add(this->button12);
this->Controls->Add(this->button11);
this->Controls->Add(this->button10);
this->Controls->Add(this->textBox1);
this->Controls->Add(this->button9);
this->Controls->Add(this->button8);
this->Controls->Add(this->button7);
this->Controls->Add(this->button6);
this->Controls->Add(this->button5);
this->Controls->Add(this->button4);
this->Controls->Add(this->button3);
this->Controls->Add(this->button2);
this->Controls->Add(this->button1);
this->Name = L"MyForm";
this->Text = L"MyForm";
this->Load += gcnew System::EventHandler(this, &MyForm::MyForm_Load);
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private: System::Void MyForm_Load(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
if(con == false) textBox1->Text = "";
con = true;
if(textBox1->Text == "Невозможно делить на ноль")textBox1->Text = "";
textBox1->Text += "1"; //вывод цифры
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
if(con == false) textBox1->Text = "";
con = true;
if(textBox1->Text == "Невозможно делить на ноль")textBox1->Text = "";
textBox1->Text += "2";
}
private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) {
if(con == false) textBox1->Text = "";
con = true;
if(textBox1->Text == "Невозможно делить на ноль")textBox1->Text = "";
textBox1->Text += "3";
}
private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) {
if(con == false) textBox1->Text = "";
con = true;
textBox1->Text += "4";
}
private: System::Void button5_Click(System::Object^ sender, System::EventArgs^ e) {
if(con == false) textBox1->Text = "";
con = true;
if(textBox1->Text == "Невозможно делить на ноль")textBox1->Text = "";
textBox1->Text += "5";
}
private: System::Void button6_Click(System::Object^ sender, System::EventArgs^ e) {
if(con == false) textBox1->Text = "";
con = true;
if(textBox1->Text == "Невозможно делить на ноль")textBox1->Text = "";
textBox1->Text += "6";
}
private: System::Void button7_Click(System::Object^ sender, System::EventArgs^ e) {
if(con == false) textBox1->Text = "";
con = true;
if(textBox1->Text == "Невозможно делить на ноль")textBox1->Text = "";
textBox1->Text += "7";
}
private: System::Void button8_Click(System::Object^ sender, System::EventArgs^ e) {
if(con == false) textBox1->Text = "";
con = true;
if(textBox1->Text == "Невозможно делить на ноль")textBox1->Text = "";
textBox1->Text += "8";
}
private: System::Void button9_Click(System::Object^ sender, System::EventArgs^ e) {
if(con == false) textBox1->Text = "";
con = true;
if(textBox1->Text == "Невозможно делить на ноль")textBox1->Text = "";
textBox1->Text += "9";
}
private: System::Void button13_Click(System::Object^ sender, System::EventArgs^ e) {
if(con == false) textBox1->Text = "";
con = true;
if(textBox1->Text == "Невозможно делить на ноль")textBox1->Text = "";
if(textBox1->Text != "0")textBox1->Text += "0";
}
private: System::Void button10_Click(System::Object^ sender, System::EventArgs^ e) { //+
if(textBox1->Text == "0" && label1->Text == "/"){ textBox1->Text = "Невозможно делить на ноль"; label1->Text = "";}
else{
if(label1->Text != ""){ //если label1 содержит знак, то производим вычисления
switch(label1->Text[0])
{
case '+':
b = a + Convert::ToDouble(textBox1->Text);
break;
case '-':
b = a - Convert::ToDouble(textBox1->Text);
break;
case '*':
b = a * Convert::ToDouble(textBox1->Text);
break;
case '/':
b = a / Convert::ToDouble(textBox1->Text);
break;
}
label2->Text = Convert::ToString(b);
a = b;
label1->Text = "+"; textBox1->Text = "";
} else {
a = Convert::ToDouble(textBox1->Text);
label1->Text = "+";
textBox1->Text = "";
}
}
}
private: System::Void button17_Click(System::Object^ sender, System::EventArgs^ e) { //=
if(textBox1->Text == "0" && label1->Text == "/"){ textBox1->Text = "Невозможно делить на ноль"; label1->Text = "";}
else{
switch(label1->Text[0])
{
case '+':
b = a + Convert::ToDouble(textBox1->Text);
break;
case '-':
b = a - Convert::ToDouble(textBox1->Text);
break;
case '*':
b = a * Convert::ToDouble(textBox1->Text);
break;
case '/':
b = a / Convert::ToDouble(textBox1->Text);
break;
}
textBox1->Text = Convert::ToString(b);
a = 0;
label1->Text = "";
con = false;
}
}
private: System::Void button11_Click(System::Object^ sender, System::EventArgs^ e) { //-
if(textBox1->Text == "0" && label1->Text == "/"){ textBox1->Text = "Невозможно делить на ноль"; label1->Text = "";}
else{
if(label1->Text != ""){
switch(label1->Text[0])
{
case '+':
b = a + Convert::ToDouble(textBox1->Text);
break;
case '-':
b = a - Convert::ToDouble(textBox1->Text);
break;
case '*':
b = a * Convert::ToDouble(textBox1->Text);
break;
case '/':
b = a / Convert::ToDouble(textBox1->Text);
break;
}
label2->Text = Convert::ToString(b);
a = b;
label1->Text = "-"; textBox1->Text = "";
} else {
a = Convert::ToDouble(textBox1->Text);
label1->Text = "-";
textBox1->Text = "";
}
}
}
private: System::Void button12_Click(System::Object^ sender, System::EventArgs^ e) { //*
if(textBox1->Text == "0" && label1->Text == "/"){ textBox1->Text = "Невозможно делить на ноль"; label1->Text = "";}
else{
if(label1->Text != ""){
switch(label1->Text[0])
{
case '+':
b = a + Convert::ToDouble(textBox1->Text);
break;
case '-':
b = a - Convert::ToDouble(textBox1->Text);
break;
case '*':
b = a * Convert::ToDouble(textBox1->Text);
break;
case '/':
b = a / Convert::ToDouble(textBox1->Text);
break;
}
label2->Text = Convert::ToString(b);
a = b;
label1->Text = "*"; textBox1->Text = "";
} else {
a = Convert::ToDouble(textBox1->Text);
label1->Text = "*";
textBox1->Text = "";
}
}
}
private: System::Void button16_Click(System::Object^ sender, System::EventArgs^ e) {//деление
if(textBox1->Text == "0" && label1->Text == "/"){ textBox1->Text = "Невозможно делить на ноль"; label1->Text = "";}
else{
if(label1->Text != ""){
switch(label1->Text[0])
{
case '+':
b = a + Convert::ToDouble(textBox1->Text);
break;
case '-':
b = a - Convert::ToDouble(textBox1->Text);
break;
case '*':
b = a * Convert::ToDouble(textBox1->Text);
break;
case '/':
b = a / Convert::ToDouble(textBox1->Text);
break;
}
label2->Text = Convert::ToString(b);
a = b;
label1->Text = "/"; textBox1->Text = "";
} else {
a = Convert::ToDouble(textBox1->Text);
label1->Text = "/";
textBox1->Text = "";
}
}
}
private: System::Void button14_Click(System::Object^ sender, System::EventArgs^ e) {
if(!textBox1->Text->Contains(",") && textBox1->Text != "")
textBox1->Text += ",";
}
private: System::Void button15_Click(System::Object^ sender, System::EventArgs^ e) {//очистка на С
a = 0;
b = 0;
label1->Text = "";
label2->Text = "";
textBox1->Text = "";
}
private: System::Void button18_Click(System::Object^ sender, System::EventArgs^ e) {
if(textBox1->Text != "") save = Convert::ToDouble(textBox1->Text);
}
private: System::Void button19_Click(System::Object^ sender, System::EventArgs^ e) {
textBox1->Text = Convert::ToString(save);
}
private: System::Void button20_Click(System::Object^ sender, System::EventArgs^ e) {
save = 0;
}
private: System::Void button21_Click(System::Object^ sender, System::EventArgs^ e) {
if(textBox1->Text == "") textBox1->Text = "-";
else if(textBox1->Text == "-") textBox1->Text = "";
else textBox1->Text = Convert::ToString(-1 * Convert::ToDouble(textBox1->Text)); //ставим "-"
}
private: System::Void button22_Click(System::Object^ sender, System::EventArgs^ e) {
textBox1->Text = "";
}
};
}