piątek, 8 grudnia 2017

A class that displays dependencies that display results and saves data to a file

.h

#include <vcl.h>
#include <stdio.h>
class prime_Numbers
{
 private:
  AnsiString file_Name;
  int size;
  bool is_First(int value);
  int sum_Table(int *tab, int size);
  int *first_Numbers;
  int *sum_Numbers;
  float *average_Numbers;
 public:
  prime_Numbers(AnsiString Name, int size_N);
  void Init();
  void Write(TListBox *LB);
  void Save();
  ~prime_Numbers();
};

.cpp
prime_Numbers::prime_Numbers(AnsiString Name, int size_N)
{

 file_Name=Name;
 size=size_N;
 first_Numbers=new int[size];
 sum_Numbers=new int[size];
 average_Numbers=new float[size];
}
void prime_Numbers::Init()
{
 int i,j,k,l;
 for(i=0;i<size;i++)
  sum_Numbers[i]=0;
 i=0;
 j=2;
 do
 {
  if(is_First(j))
  {
   first_Numbers[i]=j;
   ++i;
   l=0;
   for(k=2;k<j+1;k++)
    if(is_First(k))
     sum_Numbers[i-1]+=k;


  }
  ++j;
 }while(i<size+1);
 for(i=0;i<size;i++)
  average_Numbers[i]=(1.0*sum_Numbers[i])/(1.0*first_Numbers[i]);
}
void prime_Numbers::Write(TListBox *LB)
{
 int i;
 for(i=0;i<size;i++)
  LB->Items->Add(IntToStr(first_Numbers[i])+" - "+IntToStr(sum_Numbers[i])+" - "+
  average_Numbers[i]);

}
void prime_Numbers::Save()
{
 char *name;
 FILE *f_Name;
 int i;
 name=file_Name.c_str();
 f_Name=fopen(name,"w");
 for(i=0;i<size;i++)
 {
  fprintf(f_Name,"%d %d %.2f",first_Numbers[i],sum_Numbers[i],average_Numbers[i]);
  fprintf(f_Name,"\n");
 }
}
int prime_Numbers::sum_Table(int *tab, int size)
{
 int i,sum;
 sum=0;
 for(i=0;i<size;i++)
  sum+=tab[i];
 return sum;
}
prime_Numbers::~prime_Numbers()
{
 delete sum_Numbers;
 delete average_Numbers;
 delete first_Numbers;
}
bool prime_Numbers::is_First(int value)
{
 int i,sum;
 sum=0;
 for(i=1;i<value+1;i++)
  if(value%i==0)
   ++sum;
  if(sum==2)
   return true;
  else
   return false;
}

Example:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
 prime_Numbers p_Numbers(Edit1->Text,StrToInt(Edit2->Text));
 p_Numbers.Init();
 p_Numbers.Write(ListBox1);
 p_Numbers.Save();
}

Brak komentarzy:

Prześlij komentarz