区分结构数组和结构内数组的 C 程序
在 C 编程语言中,结构最常见的用途是结构数组。
要声明结构数组,首先必须定义结构,然后必须定义该类型的数组变量。
例如,
struct book b[10];//10 elements in an array of structures of type ‘book’
示例
以下是结构数组的 C 程序 -
struct marks{输出结果int sub1;
int sub2;
int sub3;
int total;
};
main(){
int i;
struct marks student[3] = {{20,17,11,10},
{175,23,169,10},
{27,56,27,01}};
struct marks total;
for(i = 0; i <= 2; i++){
student[i].total = student[i].sub1 +
student[i].sub2 +
student[i].sub3;
total.sub1 = total.sub1 + student[i].sub1;
total.sub2 = total.sub2 + student[i].sub2;
total.sub3 = total.sub3 + student[i].sub3;
total.total=total.total+ student[i].total;
}
printf(" STUDENT TOTAL\n\n");
for(i = 0; i <= 2; i++)
printf("Student[%d] %d\n", i+1,student[i].total);
printf("\n SUBJECT TOTAL\n\n");
printf("%s %d\n%s %d\n%s %d\n",
"Subject 1 ", total.sub1,
"Subject 2 ", total.sub2,
"Subject 3 ", total.sub3);
printf("\nGrand Total = %d\n", total.total);
}
执行上述程序时,它会产生以下输出 -
STUDENT TOTALStudent[1] 48
Student[2] 367
Student[3] 110
SUBJECT TOTAL
Subject 1 4200462
Subject 2 96
Subject 3 223
Grand Total = 525
示例
以下是结构内数组的 C 程序 -
main(){输出结果struct marks{
int sub[3];
int total;
};
struct marks student[3] =
{145,50,11,10,175,50,19,10,20,30,25,10};
struct marks total;
int i,j;
for(i = 0; i <= 2; i++){
for(j = 0; j <= 2; j++){
student[i].total += student[i].sub[j];
total.sub[j] += student[i].sub[j];
}
total.total+= student[i].total;
}
printf("STUDENT TOTAL\n\n");
for(i = 0; i <= 2; i++)
printf("Student[%d] %d\n", i+1, student[i].total);
printf("\nSUBJECT TOTAL\n\n");
for(j = 0; j <= 2; j++)
printf("Subject-%d %d\n", j+1, total.sub[j]);
printf("\nGrand Total = %d\n", total.total);
}
执行上述程序时,它会产生以下输出 -
STUDENT TOTALStudent[1] 216
Student[2] 254
Student[3] 85
SUBJECT TOTAL
Subject-1 4200548
Subject-2 130
Subject-3 71
Grand Total = 555
以上是 区分结构数组和结构内数组的 C 程序 的全部内容, 来源链接: utcz.com/z/322806.html