我遇到的问题是,即使我在 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
您传递的指针指向数组末尾之后的位置。这是一个很大的禁忌,如果你打算读取或写入它:
displayAllExam(&exams[SIZE]);
相反,只需像这样传递它:
displayAllExam(exams);
所有其他电话也是如此。
我是一名优秀的程序员,十分优秀!