[英]Why am I getting not declared in this scope error
This is what I have to do for my assignment.这是我必须为我的任务做的。 Firstly, you will need to write a function: int average(int *array, int nLen);
首先,您需要编写一个 function: int average(int *array, int nLen); which returns the average value of an array of integer values.
它返回 integer 值数组的平均值。 (To prevent overflow, it is suggested to use a long internal variable).
(为防止溢出,建议使用长内部变量)。 The Spirit Level function will run a loop.
水平仪 function 将运行一个循环。 For each iteration the Z-component of gravitational acceleration will be sampled four times at 50ms intervals and stored in a suitably sized array.
对于每次迭代,重力加速度的 Z 分量将以 50 毫秒的间隔被采样四次,并存储在适当大小的数组中。
int average (int * array, int nlen); // assuming array is int
{
long sum = 0L; // sum will be larger than an item, long for safety.
for (int i = 0; i < nlen; i++)
{
sum += array [i] ;
return ((int) sum) / nlen ;
nlen not declared in scope is the error message
there appear to be a few issues with this function.这个 function 似乎存在一些问题。 First and foremost, there are no closing curly braces for the for loop or the function.
首先,for 循环或 function 没有闭合花括号。 Additionally, you do not want a semicolon after the name and parameters of the function if you are following it with the definition.
此外,如果您在定义后跟在 function 的名称和参数后面,则不需要分号。 Try defining your function as:
尝试将您的 function 定义为:
int average(int *array, int nlen) {
long sum = 0L;
for (int i=0; i<nlen; i++) {
sum += array[i];
}
return ((int) sum) / nlen;
}
However, I would also caution you that defining sum
as a long
but then casting it back to an int
before performing the division could lead to incorrect answers, and will likely not be doing exactly what you intend.但是,我还要提醒您,将
sum
定义为long
但然后在执行除法之前将其转换回int
可能会导致错误的答案,并且可能不会完全按照您的意图进行。 For example, if sum
would indeed overflow an int
type, it will be incorrect when you cast it back to an int
.例如,如果
sum
确实会溢出int
类型,那么当您将其转换回int
时它将是不正确的。 If you want your result to be accurate, it would be best to perform the division as a long
and then cast the result to an int
to return it.如果您希望结果准确,最好将除法执行为
long
,然后将结果转换为int
以返回它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.