【发布时间】:2021-12-20 03:08:21
【问题描述】:
我尝试用 CS50 学习 C 并尝试编写考试分数计算器。我试图编写如下动态代码,但出现错误。这是我的主要代码:
#include <cs50.h>
#include <stdio.h>
const int total_exam = 3 ; // Now we are creating a constant
//Prototype
//int get_scores(void);
int main(void)
{
// get exam scores
int *all_scores;
all_scores = get_scores();
printf("Your average score is %f\n", average(total_exam, all_scores) );
}
// create an function to get exam scores of the user
int *get_scores()
{
//get exam scores of the user
int scores[total_exam];
for (int i=0;i< total_exam; i++)
{
scores[i] = get_int("What's your exam score?: "); // each int uses 4 byte space
}
return scores;
}
// create an function to calculate average
float average(int length, int array[])
{
int sum=0;
for (int i=0 ; i<length; i++)
{
sum = sum+array[i];
}
return sum / (float) length ;
}
但是当我尝试执行它时,我得到了如下错误。
scores_with_array.c:14:18: error: implicit declaration of function 'get_scores' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
all_scores = get_scores();
^
scores_with_array.c:14:16: error: incompatible integer to pointer conversion assigning to 'int *' from 'int' [-Werror,-Wint-conversion]
all_scores = get_scores();
^ ~~~~~~~~~~~~
scores_with_array.c:16:42: error: implicit declaration of function 'average' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
printf("Your average score is %f\n", average(total_exam, all_scores) );
^
scores_with_array.c:16:42: error: format specifies type 'double' but the argument has type 'int' [-Werror,-Wformat]
printf("Your average score is %f\n", average(total_exam, all_scores) );
~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%d
scores_with_array.c:22:6: error: conflicting types for 'get_scores'
int *get_scores()
^
scores_with_array.c:14:18: note: previous implicit declaration is here
all_scores = get_scores();
^
scores_with_array.c:33:12: error: address of stack memory associated with local variable 'scores' returned [-Werror,-Wreturn-stack-address]
return scores;
^~~~~~
scores_with_array.c:38:7: error: conflicting types for 'average'
float average(int length, int array[])
^
scores_with_array.c:16:42: note: previous implicit declaration is here
printf("Your average score is %f\n", average(total_exam, all_scores) );
^
7 errors generated.
我猜这是关于数组分配的,但我无法理解。你能帮忙解决这个问题吗?提前致谢。
【问题讨论】:
-
我猜不可能在 C 中返回一个数组。但如果您有任何建议,我也很乐意。我找到了这个:codeforwin.org/2017/12/pass-return-array-function-c.html