C++ Tutorial: Math class in C++/CLI. Function calculator

   In this tutorial we are going to talk about Math class in Visual C++/CLI and we will use such methods : Math::Sin (computes sine), Math::Cos(computes cosine), Math::Tan (computes tangent). And also we will write a simple program, which computes some math functions. Preparation    First of all you need to create a new Windows Forms Application project and prepare your main form for coding. In this program should be one Text Box, four Radio Buttons, two Labels and one Button Control. You can situate them as you want; the example of design of my program is above. You don’t need make changes in the settings of any control, so let’s go to coding. Code The code of the Button Clicked Event is listed below:
  1. private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
  2.  
  3.                                  double arg,res;
  4.                                  arg=Convert::ToDouble(textBox1->Text);
  5.  
  6.                                  if(radioButton1->Checked)
  7.                                  {
  8.                                          res=Math::Sin(arg);
  9.                                  }
  10.                                  if(radioButton2->Checked)
  11.                                  {
  12.                                          res=Math::Cos(arg);
  13.                                  }
  14.                                  if(radioButton3->Checked)
  15.                                  {
  16.                                          res=Math::Tan(arg);
  17.                                  }
  18.                                  if(radioButton4->Checked)
  19.                                  {
  20.                                          res=1/(Math::Tan(arg));
  21.                                  }
  22.  
  23.                                  MessageBox::Show("Result: "+res.ToString());
  24.  
  25.                          }
   Here you can see a creation of two variables of type Double. We need them to store argument of the function and its result. Later we assign to a variable “arg” value of Text Box. To make this should convert this value from String^ type to Double. The next lines of code show us “if” cases. In this area of code the program checks which function is should be computed. For example, if the user checks first radio button, the program will compute sine function. There are no cotangent function in this class, so we just do this – “res = 1 / (Math::Tan (arg))”. After the program has computed the function value it shows a Message Box with result. Below you can see the example of the program’s work. Capture

Add new comment