看他人编的程序时的疑问!
一个班级有五个学生,共学习4门课.要求编写程序完成下面3个功能
(1)求出第三门功课的平均分
(2)找出有两门以上功课不及格的学生,输出他们的学号和全部课程成绩及平均分
(3)找出平均成绩在85分以上或者全部课程成绩在80分以上的学生
提示:可以用二维数组组成结构体数组实现之
struct student
{float score1;
float score2;
float score3;
float score4;
}str[5]
程序如下:
仅供参考
fun1() {
float sum = 0;
for (int i=0; i <5; i++) {
sum += str[i].score3;
}
printf( "第三门功课平均分:%f ", sum/5);
}
fun2() {
float sum = 0;
int count = 0;
for (int i=0; i <5; i++) {
sum = str[i].score1 + str[i].score2 + str[i].score3 + str[i].score4;
count = 0;
count += ((str[i].score1 <60) ? 1 : 0);
count += ((str[i].score2 <60) ? 1 : 0);
count += ((str[i].score3 <60) ? 1 : 0);
count += ((str[i].score4 <60) ? 1 : 0);
if (count > 1) {
printf( "不及格 学号:%d, 成绩:%f,%f,%f,%f, 平均分: ", i, str[i].score1, str[i].score2, str[i].score3, str[i].score4, sum/4);
}
}
}
fun3() {
float sum = 0;
int count = 0;
for (int i=0; i <5; i++) {
sum = str[i].score1 + str[i].score2 + str[i].score3 + str[i].score4;
count = 0;
count += ((str[i].score1> =80) ? 1 : 0);
count += ((str[i].score2> =80) ? 1 : 0);
count += ((str[i].score3> =80) ? 1 : 0);
count += ((str[i].score4> =60) ? 1 : 0);
if (sum/4> =85 || count==4) {
printf( "平均成绩在85分以上或者全部课程成绩在80分以上的学生 学号:%d ", i);
}
}
}
其中:count = 0;
count += ((str[i].score1 <60) ? 1 : 0);
count += ((str[i].score2 <60) ? 1 : 0);
count += ((str[i].score3 <60) ? 1 : 0);
count += ((str[i].score4 <60) ? 1 : 0);
if (count > 1) {
中count在一开始时就为1,那count在继续执行是下面不就是都一样了吗,结果count不都为1了吗?那样的话不就错了吗?疑问???
[解决办法]
如果:对第一个学生来说:score1=59 score2=85 score3=54 score4=62
1: count = 0;
2: count += ((str[i].score1 <60) ? 1 : 0);
3: count += ((str[i].score2 <60) ? 1 : 0);
4: count += ((str[i].score3 <60) ? 1 : 0);
5: count += ((str[i].score4 <60) ? 1 : 0);
执行1,count=count+1=1
执行2,count=count+0=1
执行3,count=count+1=2
执行4,count=count+0=2
所以count=2 大于 1
if语句将执行
[解决办法]
条件语句:
int a=4,b=5,c;
c=(a> b)?1:0;
则c=0;
int a=5,b=4,c;
c=(a> b)?1:0;
则c=1;
注意:条件语句的返回值由条件的结果(true和false)决定返回?后的第一表达式得值,还是第二个表达式得值。