Builder c ++ TButton问题?

时间:2013-04-25 19:43:42

标签: c++builder

我正在使用Builder C ++ 6.

在下面的代码中,我希望我的函数KreirajPOlja()能够在按钮上生成随机的AnsiString字符,但我总是获得的只是矩阵9 * 9,只有一个生成的字符,如图所示:

enter image description here

void __fastcall TForm1::KreirajPolja()
{
                  int tr;

       for(int i=0;i<dim_x;i++)

       for(int j=0;j<dim_y;j++)  {


  Dugme[i][j]->Height=20;
  Dugme[i][j]->Width=Dugme[i][j]->Height;
  Dugme[i][j]->Left=i*Dugme[i][j]->Height;
  Dugme[i][j]->Top=j*Dugme[i][j]->Height;
  Dugme[i][j]->Parent=this;
              tr=PostaviRandom();
  Dugme[i][j]->Caption= NizSlova[tr];



}


    Button1->Caption="submit";
    Button1->Enabled=false;




  Form1->Width=dim_x* 20+5;
   Form1->Height=(dim_y+2)* 20+25;

}
//---------------------------------------------------------------------------


                 int __fastcall TForm1::PostaviRandom(){
                        int k;
                     srand(time(0));
                     k=rand()%sizeof(NizSlova);

                 return k;}   

这是下面的cpp代码

        #ifndef Unit1H
        #define Unit1H
//---------------------------------------------------------------------------
     #include <Classes.hpp>


        #include <Controls.hpp>

       #include <StdCtrls.hpp>

        #include <Forms.hpp>

         #include <time.h>

       //--- ------------------------------------------------------------------------

              class TForm1 : public TForm
               {

            __published:    // IDE-managed Components

        TButton *Button1;

       void __fastcall FormCreate(TObject *Sender);

        public:     // User declarations

          TButton*** Dugme;
            TImage *** Slike;
         TEdit *brojac;
       int dim_x, dim_y;
       int vrijeme,kr;
       int BrojSlova, br;
       AnsiString NizSlova;


    __fastcall TForm1(TComponent* Owner);
    void __fastcall KreirajSlova();
    void __fastcall AlocirajProstor();
    void __fastcall BrisiProstor();
    void __fastcall AlocirajProstorZaSlova();
    void __fastcall BrisiProstorZaSlova();


    void __fastcall KreirajPolja();
    virtual   int __fastcall PostaviRandom();
    AnsiString __fastcall DajSlovo();



       };
        //---------------------------------------------------------------------------
        extern PACKAGE TForm1 *Form1;
          //---------------------------------------------------------------------------
             #endif

1 个答案:

答案 0 :(得分:2)

请勿在循环中调用srand。在程序开始时调用一次。

每次拨打srand时,都会重置随机数生成器。由于您每次都使用相同的参数调用它(您的代码运行时间不到一秒,因此time(NULL)的值不会更改),您可以从rand()得到相同的结果。

除非您有意复制旧的随机数序列,否则无需在同一程序中多次调用srand