问题链接: https://www.codzilla.org/questions?qid=40
编写代码来查找数组中所有元素的平均值。
此代码已提供且无法编辑:
int e; /* Number of elements in array */
int *a; /* Array of elements */
float average; /* average to be calculated */
这是我尝试过的:
int i = 0;
for(i = 0; i < e; i++)
{
average += *(a + i);
}
average = average / e;
我希望代码能够正常工作并给我正确的答案,但它在编译过程中给了我以下错误,我无法调试。
您的代码无法编译! code_5945838145861895779.c:在函数“calculateAverage”中: code_5945838145861895779.c:15:1: 错误:在“return”之前应有“;” code_5945838145861895779.c:15:18:错误:“}”标记之前的预期表达式 code_5945838145861895779.c:15:18:错误:“}”标记之前的预期表达式
最佳答案
您的代码中有很多基本问题。我建议您引用任何好的 C
并了解基本的 C
程序和指针的工作原理。
首先,我在您的代码中没有看到 main()
。 main()
的原型(prototype)是
int main(void) {
/* some code */
return 0;
}
其次,这里
int *a; /* Array of elements */
int
指针 a
未初始化且它没有任何有效内存,因此当您执行 *(a+i)
时它会导致段错误,要解决此问题,您应该分配 dynamic memory首先是a
。
第三点,这里
float average;
默认情况下average
包含什么?它是一些垃圾或垃圾数据。应使用 0
进行初始化。
示例代码
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int e; /* how many e ? you should assign it here or take at runtime */
printf("enter the number of elements in the array \n");
scanf("%d",&e);
int *a; /* Allocate memory so that it can hold some values */
a = malloc(e * sizeof(int)); /* allocating memory for e integer equal to e*sizeof(int) bytes */
/* check if malloc was successful or not */
if(a == NULL) {
printf("memory allocation was failed \n");
exit(0);
}
else {
printf("memory allocation is success.. Can proceed further\n ");
/* put the data into dynamically allocated memory */
for(int i=0; i < e; i++) {
scanf("%d", &a[i]);
}
}
float average = 0; /* initialize with 0 */
int i=0;
for(i=0;i<e;i++) {
average += *(a+i);
}
average=average/e; /* average is of float type, e is of int type, doing / operation b/w two different types ? Result may not be as expected due to implicit typeconversion, do explicit typeconversion */
printf("o/p : %f\n", average);
/* job is done with dynamically created array a ? Free it */
free(a);
return 0;
}
关于c - 如何针对这个问题编写代码以避免编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55310832/