[英]Display the individual sum of all the data linked list
I am writing a data structure program using c++ .我正在使用 c++ 编写数据结构程序。 This is my code to display sum of quiz I and II of all students.
这是我的代码,用于显示所有学生的测验 I 和 II 的总和。 But it is only display the sum of the first student.
但它只显示第一个学生的总和。
int totalscore(){
double sum;
node *pcurrent;
pcurrent=pfirst;
while(pcurrent!=NULL)
{
sum= (pcurrent->quizI + pcurrent->quizII);
pcurrent =pcurrent->pnext++;//move
}
cout<<"The individual sum are " <<sum ;
};
int main() {
linkedlist apt;
apt.insert("643431 ", 50, 40);
apt.insert( "655222",100, 20);
apt.insert( "655444",70, 30 );
apt.insert( "651515",10, 30);
apt.insert(" 644444", 70, 32);
apt.displaylist();
apt.totalscore();
return 0;
}
Thank for helping感谢帮助
You're not moving to the next node correctly.您没有正确移动到下一个节点。
Change this line改变这一行
pcurrent = pcurrent->pnext++;
to到
pcurrent = pcurrent->pnext;
And, for the individual sum of each student in the linked list separately, you have to calculate the sum and print it in the loop for all the nodes in the loop like this:而且,对于链表中每个学生的单独总和,您必须计算总和并将其打印在循环中的所有节点的循环中,如下所示:
void totalscore() // no return value
{
node *pcurrent = pfirst;
while ( pcurrent != NULL )
{
double sum = (pcurrent->quizI + pcurrent->quizII);
cout << "Sum: " << sum << '\n';
pcurrent = pcurrent->pnext;
}
}
The method name totalscore()
with the return type implies that you want to return the sum of all the students' score in the likned list eg:带有返回类型的方法名称
totalscore()
意味着您要返回喜欢的列表中所有学生的分数总和,例如:
double totalscore() // sum is double type so return the same
{
double sum = 0.0;
node *pcurrent = pfirst;
while ( pcurrent != NULL )
{
sum += (pcurrent->quizI + pcurrent->quizII);
pcurrent = pcurrent->pnext;
}
cout << "Sum " << sum << '\n';
return sum; // return the sum when calculated
}
If you want to return the individual sum of all the students from the function separately:如果您想从函数中分别返回所有学生的个人总和:
std::vector
;std::vector
类的容器中; or,sum
in the node itself and calculate the sum as you store data and use that whenever you need the sum.sum
,并在存储数据时计算总和,并在需要总和时使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.