我遇到的问题是即使我在main中将名为exam []的数组设置为零,当我调用函数displayAllExam()时,只有一些设置为零而其他设置为可能代表ram空格的随机数。这搞乱了我的displayExamAverage()函数,因为当我运行代码时,我可以向数组添加值,但如果我不添加50个值,那么将会有随机数。我还真的停留在displayHighLow函数上,它可以找到数组的最高和最低值
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define pause system("pause")
#define cls system("cls")
#define flush fflush(stdin)
#define SIZE 50
//Lets Prototype
int getChoice();
void displayMenu();
void addScores(int a[],int *c);
void displayAllExam(int a[]);
void displayExamAverage(int a[], int *c);
void displayHighLow(int a[], int *c);
main(){
int exams[SIZE] = {0}, counter = 0;
char choice;
do {
choice = getChoice();
switch(choice){
case 1:
addScores(&exams[SIZE],&counter);
break;
case 2:
displayExamAverage(&exams[SIZE],&counter);
break;
case 3:
displayHighLow(&exams[SIZE], &counter);
break;
case 4:
displayAllExam(&exams[SIZE]);
break;
}
}while (choice != 5);
}//end main
int getChoice(){
int result = 0;
do{
displayMenu();
scanf_s("%i", &result);
if(result < 1 || result >5 ){
printf("Invalid Selection, please enter a number between 1 and 5\n");
pause;}
} while(result < 1 || result > 5);
return result;
}//end getChoice
void displayMenu() {
cls;
printf("MAIN MENU\n\n");
printf("1: add an exam score\n");
printf("2.Display exam average\n");
printf("3.Display High and Low score\n");
printf("4.Display all scores\n");
printf("5.Quit\n\n");
printf("Enter your choice: \n\n");
return;
}//end display menu
void addScores(int a[SIZE],int *c){
int i=0;
printf("please enter your score..");
scanf_s("%i", &a[i]);
}//end add scores
void displayExamAverage(int a[],int *c){
float average, total = 0.0;
int i;
for(i=0; i < *c; i++)
total = total + a[i];
average = total/ *c;
printf("%f",average);
pause;
}//end displayExamAverage
void displayHighLow(int a[],int *c){
int high= a[0], low= a[0];
int i,x,y;
for(i=0; i < *c; i++){
if(a[*c]> a[0])
high = a[i];
}
for(i=0; i < *c; i++){
if(a[*c]<a[0])
low = a[i];
}
printf("The low is %i", low);
printf("The high is %i", high);
pause;
}//end DisplayHighLow
void displayAllExam(int a[SIZE]){
int i;
for(i=0;i < SIZE; i++)
printf("the %i score is %i\n",i+1,a[i]);
pause;
}//end displayAllExam
答案 0 :(得分:2)
您正在将指针传递到阵列结束后的位置。如果您打算阅读或写信,这是一个很大的禁忌:
displayAllExam(&exams[SIZE]);
相反,只需将它传递给它:
displayAllExam(exams);
所有其他电话也一样。