C++ Tutorial: Multiplication Checker. Random in C++/CLI
Submitted by Bright777 on Friday, February 28, 2014 - 21:46.
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.
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.
- private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
- int a,b;
- Random^ rd=gcnew Random;
- a=rd->Next(20);
- b=rd->Next(20);
- label1->Text=a.ToString();
- label3->Text=b.ToString();
- }
- private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
- int a,b, ures,res;
- a=Convert::ToInt32(label1->Text);
- b=Convert::ToInt32(label3->Text);
- res=a*b;
- ures=Convert::ToInt32(textBox1->Text);
- if(res==ures)
- MessageBox::Show("Correct!!!");
- else
- MessageBox::Show("Incorrect");
- }
Add new comment
- 171 views