找回密码
 注册
搜索
热搜: 回贴
  • 前程无忧官网首页 有什么好的平台可以
  • 最新的销售平台 互联网营销的平台有哪
  • 制作网页的基本流程 网页制作和网页设
  • 【帝国CMS】输出带序号的列表(数字排
  • 网站建设公司 三一,中联,极东泵车的
  • 织梦 建站 织梦网站模版后台怎么更改
  • 云服务官网 哪些网站有免费的简历模板
  • 如何建网站要什么条件 建网站要用什么
  • 吉林市移动公司电话 吉林省退休人员网
  • 设计类毕业论文 网站设计与实现毕业论
查看: 806|回复: 3

[求助]这个c++问题到底错在哪里了?谢谢

[复制链接]
发表于 2009-11-4 01:13:53 | 显示全部楼层 |阅读模式 IP:江苏扬州
谁帮我看下这个程序,很简单,就想求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,反而错了。。。
发表于 2009-11-4 01:13:54 | 显示全部楼层 IP:江苏扬州
以下是引用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个学生的计算了
回复

使用道具 举报

发表于 2009-11-4 01:13:55 | 显示全部楼层 IP:江苏扬州
恩,想出来了,应该是这两句:
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],但是应该怎么修改才能正确显示呢?
回复

使用道具 举报

发表于 2009-11-4 01:13:56 | 显示全部楼层 IP:江苏扬州
for(int i=0;i<n;i++)
stu.total();
cout<<"the sum of the student's score is: "<<stu.total()<<endl;
cout<<"the average score of "<<n<<" students is "<<stu.average()<<endl;

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

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|小黑屋|最新主题|手机版|微赢网络技术论坛 ( 苏ICP备08020429号 )

GMT+8, 2024-10-1 01:25 , Processed in 0.202789 second(s), 13 queries , Gzip On, MemCache On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表