【发布时间】:2020-07-07 06:00:54
【问题描述】:
我还是 C 编程的新手,需要弄清楚为什么当我输入“c”选项时,程序没有打印出程序中输入的成绩。我没有看到我缺少的东西,如果有人看到我缺少的东西,可以告诉我吗?
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Add all of the variables and the array for the grades I want to enter.
char choice;
int gradeScore = 0;//percentage
//int gradeArray[100];//percentArrray //Comment Out
int gCount = 0,i;//count
//Allocate dynamic memory point using gradeArray.
int *gradeArray = (int*)malloc(sizeof(int));
/*The for loop is set to enable the user to enter no more than 100 grades. This is because the gradeArray variable
limit is set to 100. This will then loop through until the user has entered up to 100 grades to ensure there
is no buffering issue.*/
for (gCount = 0; gCount < 100;)
{
/*This prompts the user for a choice that enables them to either enter another grade or exit the program and
print the grades. It also reads the choice entered by the user.*/
printf("******************Enter Choice Selection in Parenthesis******************");
printf("\n\n To add grades, enter choice (a)");
printf("\n When finished entering grades, enter choice (c) \n \nEnter Choice: ");
scanf(" %c", &choice); //space is entered to ensure the compiler does not read whitespaces
/* Then I use an if with the condition set to a valid choice of 'a'. Then I prompt the user
to enter a grade, read it and move on to the next if statement.*/
if(choice == 'a')
{
printf("\nEnter grade: ");
scanf(" %d", &gradeScore);
/*If the grade entered does meet the if condition statement below it is added to the gCount
of grades entered. This will allow all of the grades entered to be printed with the exit condition.*/
if(gradeScore <= 100 && gradeScore >= 0)
{
gradeArray = realloc(gradeArray, sizeof(int) * gCount);
}
}
//The last if statement prints out each grade on a new line when the user choice is c.
if(choice == 'c')
{
break;
}
}
printf("Grades are:\n");
for(i = 0; i < gCount ; i++)
{
printf(" %d\%%\n", gradeArray[i]);
}
free(gradeArray);
return 0;
}
谢谢你, 安妮特
【问题讨论】:
-
您正在制作一个包含 one
int的数组?为什么不从一些合理的默认值开始,在达到该限制后将大小调整约 1.5 倍? -
当 gcount == 0 时,
realloc(gradeArray, sizeof(int) * gCount)是一个问题。这看起来像是一个错误。 -
您能否提供您的确切输入和结果?
-
请注意
printf(" %d\%%\n", gradeArray[i]);应该是printf(" %d%%\n", gradeArray[i]);您可以通过放置两个"%%"来逃避%格式规范。 -
******************在括号中输入选项选择******************到添加成绩,输入选项 (a) 输入完成绩后,输入选项 (c) 输入选项:a 输入成绩:34 ******************在括号中输入选项选项* ***************** 要添加成绩,请输入选项 (a) 输入完成绩后,输入选项 (c) 输入选项:c 成绩为:进程返回 0 (0x0) 执行时间:4.766 s 按任意键继续。
标签: c