一:观察(助于对题意的理解)
1.要求
1)本题总时间限制:1000ms,内存限制:65536kB。
2)求班上所有学生的平均年龄,保留到小数点后两位。
3)第一行有一个整数n(1<= n <= 100),表示学生的人数。其后n行每行有1个整数,表示每个学生的年龄,取值为15到25。输出一行,该行包含一个浮点数,为要求的平均年龄,保留到小数点后两位。
2.参照
1)样例
·
二:分析 (按照观察的例子分析其中的问题)
1.应该用到什么
1)第一行有一个整数n(1<= n <= 100),表示学生的人数。此处需要一个整数变量n来表示学生的人数。
2) 其后n行每行有1个整数,表示每个学生的年龄,取值为15到25。此处需要一个for循环来解决n数值不一的问题。
3)输出一行,该行包含一个浮点数,为要求的平均年龄,保留到小数点后两位。此处需要一个小数变量pj来表示平均年龄。
2.根据1的分析来推理程序代码
1)int n
2) for(int i=1;i<=n;i++)
3) float(或double)pj
三.尝试编写程序
#include <stdio.h> #include <stdlib.h> int main() { int n,b,c,s; float pj; scanf("%d",&n); s=0; for(b=1;b<=n;b++) { scanf("%d",&c); s=s+c; } pj=1.0*s/n; printf("%.2f",pj); }
此时在Dev-C++中按照样例输入运行输出是一致的,但不能确定提交是否AC,所以要进行随机数值检测。
Dve-C++
为了方便检测速度与随机性,需要创建一个数据生成器。
可以应用freopen来进行快捷存档。
freopen("c:\\test.in","r",stdin); //输入运用c盘中的test,in的数值
freopen("c:\\test.out","w",stdout); //输出自行新建一个文件在c盘中显示数值
保证随机可以用time做种子,因为time每时每刻都在变化,所以是最好的随机种。
结果如下
srand((int)time(0));
通过编写得
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
freopen("e:/cx/cx/noi/1.5/prog/1/test1.in","w",stdout);
int i,n,a;
srand((int)time(0));
n=1;
while(n)
{
n=rand()%100;
if(n>0)
{
printf("%d\n",n);
break;
}
}
for(i=1;i<=n;)
{
a=rand()%25;
if(a>=15)
{
printf("%d ",a);
i++;
}
}
}
按照此程序生产的数值,再来测试,测试需要将程序添加freopen("c:\\test.in","r",stdin);
#include <stdio.h>
#include <stdlib.h>
int main()
{
freopen("e:/cx/cx/noi/1.5/prog/1/test1.in","r",stdin);
int n,b,c,s;
float pj;
scanf("%d",&n);
s=0;
for(b=1;b<=n;b++)
{
scanf("%d",&c);
s=s+c;
}
pj=1.0*s/n;
printf("%.2f",pj);
}
经过测试,发现全都正确,这时候就有%90的几率是正确代码了。经提交,确定AC。