| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 436 人关注过本帖
标题:[求助]这个c++问题到底错在哪里了?谢谢
只看楼主 加入收藏
lusamy
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2006-10-25
收藏
 问题点数:0 回复次数:3 
[求助]这个c++问题到底错在哪里了?谢谢


谁帮我看下这个程序,很简单,就想求3个学生成绩的总分及平均分,但输入2,结果是正确的,输入3为什么不行啊?

#include <iostream>
using namespace std;

class Student
{
public:
Student(int n,int a,float s): num(n),age(a),score(s){}
float total();
float average();

private:
int num,age,score;
static float sum;
static int count;
};

float Student::total()
{
sum=sum+score;
count++;
return sum;
}

float Student::average()
{
return (sum/count);
}

float Student::sum=0;
int Student::count=0;

int main()
{
Student stu[3]=
{
Student(1001,21,11),
Student(1002,22,12),
Student(1005,28,13),
};

int n;
cout<<"please enter the number of the student: ";
cin>>n;
for(int i=0;i<n;i++)
stu[i].total();
cout<<"the sum of the student's score is: "<<stu[i].total()<<endl;
cout<<"the average score of "<<n<<" students is "<<stu[i].average()<<endl;
return 0;
}

为什么输入2,答案才是正确的,输入3,反而错了。。。

2006-11-18 14:49
wangxiang
Rank: 2
等 级:新手上路
威 望:5
帖 子:376
专家分:0
注 册:2006-3-28
收藏
得分:0 

以下是引用lusamy在2006-11-18 14:49:07的发言:

cin>>n;
for(int i=0;i<n;i++)
stu[i].total();
cout<<"the sum of the student's score is: "<<stu[i].total()<<endl;
cout<<"the average score of "<<n<<" students is "<<stu[i].average()<<endl;


当你输入3时,for循环已经统计完了3个学生的成绩。
退出循环时,i值为3,你调用stu[3].total结果就是未定义了。
因此,你的程序只要输入2,就能完成3个学生的计算了

[此贴子已经被作者于2006-11-18 15:10:50编辑过]


2006-11-18 15:10
lusamy
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2006-10-25
收藏
得分:0 
恩,想出来了,应该是这两句:
cout<<"the sum of the student's score is: "<<stu[i].total()<<endl;
cout<<"the average score of "<<n<<" students is "<<stu[i].average()<<endl;
出现了重复调用对象stu[i],但是应该怎么修改才能正确显示呢?
2006-11-18 15:10
四处漂泊
Rank: 1
等 级:新手上路
帖 子:25
专家分:0
注 册:2005-11-28
收藏
得分:0 

[QUOTE]for(int i=0;i<n;i++)
stu[i].total();
cout<<"the sum of the student's score is: "<<stu[i].total()<<endl;
cout<<"the average score of "<<n<<" students is "<<stu[i].average()<<endl;
[/QUOTE]
for(int i=0;i<n;i++)
stu[i].total();//这里调用了一次stu.total();
cout<<"the sum of the student's score is: "<<stu[i].total()<<endl;//这里又调用了一次stu[i].total()等于就是重复调用了函数sum=sum+score;
改为:
for(int i=0;i<n;i++)

{ cout<<"the sum of the student's score is: "<<stu[i].total()<<endl;

cout<<"the average score of "<<i<<" students is "<<stu[i].average()<<endl;
cout<<"---------------------------------------"<<endl;
}


2006-11-18 20:29
快速回复:[求助]这个c++问题到底错在哪里了?谢谢
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.012662 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved