我想计算着墨列表元素的标准偏差,所以我写了一个函数来计算平均值和总和,然后用公式计算标准差,但是我得到了错误" 0xC0000005:访问冲突读取位置0x00000000。"在第46行,
sd += ((first->info)-average)*((first->info-average);
为什么会出现这个问题,有没有办法摆脱它? 我的代码如下:
class Node
{
public:
int info;
Node* next;
int value;
};
class List:public Node
{
Node *first,*last;
public:
List()
{
first=NULL;
last=NULL;
}
void create();
void insert();
void delet();
void display();
void search();
void sum();
void sd();
};
void List::sd()
{
system("cls");
cout<<"The Linked List Operations Program";
cout<<"\n==========================================================="<<endl;
Node *temp=first;
int sd = 0;
int length=0;
while(temp!=NULL)
{
length++;
temp=temp->next;
}
int sum = 0;
while (first != NULL)
{
sum += first->info;
first = first->next;
}
int average;
average = (sum/length);
sd += ((first->info)-average)*((first->info-average);
first=first->next;
cout<<average;
cout<<"The standard diviation is " <<sqrt(sd)/10 ;
cin.get();
cin.get();
}
int main()
{
system("cls");
int m;
List l;
Node *first;
int ch;
l.sd();
return 0 ;
}
void List::create()
{
system("cls");
cout<<"The Linked List Operations Program";
cout<<"\n==========================================================="<<endl;
Node *temp;
temp=new Node;
int n;
cout<<"\nEnter an element to create the first node of the linkedlist:";
cin>>n;
temp->info=n;
temp->next=NULL;
if(first==NULL)
{
first=temp;
last=first;
}
else
{
last->next=temp;
last=temp;
}
}
void List::insert()
{
system("cls");
cout<<"The Linked List Operations Program";
cout<<"\n==========================================================="<<endl;
Node *prev,*cur;
prev=NULL;
cur=first;
int count=1,pos,ch,n;
Node *temp=new Node;
cout<<endl<<"ADDED";
system("cls");
temp->info=rand();
temp->next=NULL;
last->next=temp;
last=temp;
}