mad*_*Lad 3 c average function
该计划是关于平均功能.每当我构建它时,我在下面的avg_array函数(加粗的函数)中得到错误"错误:预期';',','或'''之前的数字常量".感谢帮助,谢谢!
#include <stdio.h>
#define SIZE 5
// Prototypes
int avg_array (int*, int);
main()
{
int values[SIZE];
int avg;
int i;
printf("Enter 5 numbers please. \n");
for(i=0; i<SIZE; i++)
{
scanf("%d", &values[i]);
}
avg = avg_array(values, SIZE);
printf("\n The avg of the array is %d \n", avg);
getchar();
getchar();
} // end main()
/* Implement avg_array() WHERE THE ERROR PERTAINS */
avg_array(int my_array[], int SIZE)
{
int sum;
int i;
int fxn_average;
for(i=0; i<SIZE; i++)
{
sum = sum + my_array[i];
}
fxn_average = (sum/SIZE);
return (fxn_average);
}
Run Code Online (Sandbox Code Playgroud)
您正在使用标识符SIZE
作为参数.这也是5
由预处理器转换为的宏.在预处理器应用宏之后,它看起来像
avg_array (int my_array[], int 5)
Run Code Online (Sandbox Code Playgroud)
由于5
是数字常量而不是标识符,因此会生成错误.更改变量名称.
看起来你还有一个缺少返回类型的函数签名,它应该与上面声明的原型相匹配.试试这个:
int avg_array (int *my_array, int size)
{
int sum = 0;
int i;
for(i=0; i<size; i++)
{
sum = sum + my_array[i];
}
return sum/size;
}
Run Code Online (Sandbox Code Playgroud)
该变量sum
应初始化为0. fxn_average
不需要局部变量,因为您可以return sum/size;
在最后使用.
我将第一个参数的类型从int[]
(array of int
)更改为int *
(指向int
),因此函数定义与问题中给出的原型匹配.该函数被声明为
int avg_array (int*, int);
Run Code Online (Sandbox Code Playgroud)
这些参数没有标识符; 只指定了他们的类型.这是有效的C,但许多风格指南都规定了它,因为命名参数有助于读者理解意义或意图.例如,如果您正在编写编程接口,那么程序员可能会看到头文件中的函数原型.必须清楚编写正确函数调用的参数是什么.无论如何,添加标识符看起来像:
int avg_array (int *my_array, int size);
Run Code Online (Sandbox Code Playgroud)
这与我上面使用的定义相同.