2015-05-27 41 views
-2

我应该制作2个构建图形的代码。我已经有1。它只是建立图片:构建图形并使用链表

double a = LabeledEdit1 -> Text.ToDouble(); 
    double S = LabeledEdit2 -> Text.ToDouble(); 
    Series1-> Clear(); 
    for(float i = -5; i <= 5; i+=S) { 
    float y = exp(i*log(a)); 
    Series1->AddXY(i , y ,"",clBlue); 
    } 

但第二个任务是对我来说更难。我应该做新的结构

struct K { 
    double x; 
    double y; 
    struct K *next; 
}; 

然后做链接列表。然后将点(x,y)放到StringGrid中,然后构建图形。我做了一些代码,但它不能正常工作。需要帮忙。

K* head = 0; 
    K* curr = 0; 
    K* vyv; 
    double x = 1; 
    double y; 
    double a = LabeledEdit1 -> Text.ToDouble(); 
    double S = LabeledEdit2 -> Text.ToDouble(); 
    int i=0; 
    for (i = 0; i < 500; ++i) { 
    if (i==0) { 
     y = exp(x*log(a)); 
     head = (K*) malloc(sizeof K); 
     head->x = x; 
     head->y = y; 
     head->next = NULL; 
    } 
    else { 
     y = exp(x*log(a)); 
     curr = (K*) malloc(sizeof K); 
     curr->x = x; 
     curr->y = y; 
     curr->next = NULL; 
    } 
    x++; 
    } 
    vyv = head; 
    i = 0; 
    int l = 0, I = 0; 
    while(vyv){ 
    x = vyv->x; 
    StringGrid1->Cells[i][0] = x; 
    y = vyv->y; 
    StringGrid1->Cells[i][1] = y; 
    Series1->AddXY(i , y ,"",clBlue); 
    vyv = vyv->next; 
    ++i; 
    } 
+0

如果您使用了* modern *编译器,则可以使用'std :: list',而不用担心创建和调试自己的链表。 –

+0

C++ Builder 6有'std :: list'。 –

回答

0

你的第一个循环是不节点连接在一起,所以它们都具有的一个NULLnext,因此你的第二个循环运行仅1次迭代(对于head节点)。您也应该使用new而不是malloc()

试试这个:

K* head = 0; 
K* curr = 0; 
K* last = 0; 
double x = 1; 
double y; 
double a = LabeledEdit1 -> Text.ToDouble(); 
double S = LabeledEdit2 -> Text.ToDouble(); 
int i; 
for (i = 0; i < 500; ++i) { 
    y = exp(x*log(a)); 
    curr = new K; 
    curr->x = x; 
    curr->y = y; 
    curr->next = NULL; 
    if (!head) head = curr; 
    if (last) last->next = curr; 
    last = curr; 
    x++; 
} 
curr = head; 
i = 0; 
int l = 0, I = 0; 
while(curr){ 
    x = curr->x; 
    StringGrid1->Cells[i][0] = x; 
    y = curr->y; 
    StringGrid1->Cells[i][1] = y; 
    Series1->AddXY(i , y ,"",clBlue); 
    curr = curr->next; 
    ++i; 
} 

而当你使用的是他们做不忘记释放的节点:

curr = head; 
while(curr){ 
    K *next = curr->next; 
    //... 
    delete curr; 
    curr = next; 
} 

虽这么说,你应该使用std::list类代替,让它为您处理内存管理:

#include <list> 

struct K { 
    double x; 
    double y; 
}; 

std::list<K> myList; 

double x = 1; 
double y; 
double a = LabeledEdit1 -> Text.ToDouble(); 
double S = LabeledEdit2 -> Text.ToDouble(); 
int i; 
for (i = 0; i < 500; ++i) { 
    y = exp(x*log(a)); 
    K curr; 
    curr.x = x; 
    curr.y = y; 
    myList.push_back(curr); 
    x++; 
} 
i = 0; 
int l = 0, I = 0; 
for(std::list<K>::iterator iter = myList.begin(); iter != myList.end(); ++iter) 
{ 
    x = iter->x; 
    StringGrid1->Cells[i][0] = x; 
    y = iter->y; 
    StringGrid1->Cells[i][1] = y; 
    Series1->AddXY(i , y ,"",clBlue); 
    ++i; 
}