C++ Tutorial: Multiplication Checker. Random in C++/CLI

   Today we will talk about random numbers in C++/CLI. Also I will show you a simple program, where I have used random numbers generator. First of all I should tell some words about the program. The main purpose of it will be to check your math knowledge in multiplication. It will generate two random numbers and you should multiply them and write the result. If the result is correct, program will show you the message “Correct”. Else you will see message box with such text – “Incorrect!!” So let’s learn math :) and write the program. Preparation    As always create a new Windows Forms Application project. After that you need to put on your form 4 Labels, 1 Text Box and 2 Buttons. Change text of two labels. For first write “X” and for the other write “=”. Also you need to rename buttons. Change the text of the first button to “Generate”. By clicking on this button, program will generate random numbers in the labels. Then set text of second button to “Check”. Using this button we can check if we were right or not. Code    Here you can see the code of the first button. We create two integer variables to represent random numbers. Then we use Random object to get random numbers and assign them to our variables. After that we change label values.
  1. private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
  2.  
  3. int a,b;
  4.  
  5. Random^ rd=gcnew Random;
  6.  
  7. a=rd->Next(20);
  8. b=rd->Next(20);
  9.  
  10. label1->Text=a.ToString();
  11. label3->Text=b.ToString();
  12.  
  13. }
   Below you can see the code of the button “Check”. Here we get values of random numbers from the labels, multiply them and check the user’s input.
  1. private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
  2.  
  3. int a,b, ures,res;
  4.  
  5. a=Convert::ToInt32(label1->Text);
  6. b=Convert::ToInt32(label3->Text);
  7.  
  8. res=a*b;
  9.  
  10. ures=Convert::ToInt32(textBox1->Text);
  11.  
  12. if(res==ures)
  13. MessageBox::Show("Correct!!!");
  14. else
  15. MessageBox::Show("Incorrect");
  16.  
  17. }

Add new comment