我创建了一个简单的程序,用于显示大学生数据,并将分数累积计算为一个分数(a、B、C、D、E(,并使用struct(我禁止使用Array of struct创建(,所以问题是其中一个输出"grade"在用%s打印时给出(null(结果,而在用%C打印时给出完全空白的结果。顺便说一下,"等级"数据的类型是char。这是完整的代码。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <ctype.h>
struct student
{
char nim[11];
char name[100];
char subjectCode[5];
int sks;
char grade;
}studentScore[100];
bool cekKarakter(char input[])
{
for(int x = 0; x < strlen(input); x++)
{
if(isdigit(input[x]))
return false;
}
return true;
}
bool cekNumeric(char input[])
{
for(int x = 0; x < strlen(input); x++)
{
if(input[x] >= 48 && input[x] <= 57)
return false;
}
return true;
}
int main()
{
int n;
printf("Input number of Student Data: ");
scanf("%d", &n);
fflush(stdin);
printf("nn");
for(int i = 1; i <= n; i++)
{
do
{
printf("NIM [Hanya numerik][10 Digit]: ");
gets(studentScore[i].nim);
fflush(stdin);
}
while(strlen(studentScore[i].nim) != 10 ||
cekNumeric(studentScore[i].nim));
printf("n");
do
{
printf("Name [Hanya karakter]: ");
gets(studentScore[i].name);
fflush(stdin);
}
while(strlen(studentScore[i].name) < 5 || strlen(studentScore[i].name) >
30 || cekKarakter(studentScore[i].name) == false);
printf("n");
do
{
printf("Subject Code [Must 5 length]: ");
gets(studentScore[i].subjectCode);
fflush(stdin);
}
while(strlen(studentScore[i].subjectCode) != 5);
printf("n");
do
{
printf("SKS [Min 2|Max 8]: ");
scanf("%d", &studentScore[i].sks);
fflush(stdin);
}
while(studentScore[i].sks < 2 || studentScore[i].sks > 8);
printf("n");
int score[5];
int WeightGrade = 0;
printf("Input 5 College Subject Score:nn");
for(int z = 0; z < 5; z++)
{
do
{
printf("Input Score[%d][Must be between 0 and 100]: ", z + 1);
scanf("%d", &score[z]);
}
while(score[z] < 0 || score[z] > 100);
WeightGrade += score[z];
}
if(WeightGrade / 25 == 4)
{
studentScore[i].grade = 'A';
}
else if(WeightGrade / 25 >= 3 && WeightGrade / 25 < 4)
{
studentScore[i].grade = 'B';
}
else if(WeightGrade / 25 >= 2 && WeightGrade / 25 < 3)
{
studentScore[i].grade = 'C';
}
else if(WeightGrade / 25 >= 1 && WeightGrade / 25 < 2)
{
studentScore[i].grade = 'D';
}
else if(WeightGrade / 25 == 0)
{
studentScore[i].grade = 'E';
}
}
printf("nStudent Datan");
for(int i = 1; i <= n; i++)
{
printf("NIM: %snName: %snSubject Code: %snSKS: %dnGrade: %sn",
studentScore[i].nim,
studentScore[i].name,
studentScore[i].subjectCode,
studentScore[i].sks,
studentScore[i].grade);
}
getchar();
return 0;
}
这是程序运行时的图像(空(使用%s作为打印的输出结果
在您的代码中,WeightGrade实际上是所有等级的总和,因此对于您的示例,WeightGrade=370。
370/25不属于任何选项,所以studentScore[i].grade没有任何价值。为了防止出现这种情况,请始终输入显示错误的else子句
由于您有5个值,您应该除以5*25=125,如WeightGrade/125
同样对于printf,您不应该在字符值上使用%s,您应该使用%c