[英]This is a c code to find the average in an array of 50 elements using a function
#include <stdio.h>
#include <stdlib.h>
float Findaverage(float n,float numbers[]) {
float sum = 0;
for (int j = 0; j < n; j++) {
sum += numbers[j];
}
printf("The average number of the array is: %f", sum/n);
}
int main() {
int sum = 0;
float numbers[50];
float average;
printf("Enter 50 elements: ");
// taking input and storing it in an array
for(int i = 0; i < 50; ++i) {
scanf("%f", &numbers[i]);
}
average = Findaverage(50,numbers[50]);
printf("\nThe average number of the array is: %f", average );
return 0;
}
The output gives an error "passing 'float' to parameter of incompatible type 'float *'; take the address with &".输出给出错误“将‘float’传递给不兼容类型‘float *’的参数;使用&获取地址”。 Why is this?
为什么是这样?
For starters the function Findaverage
returns nothing.对于初学者来说,函数
Findaverage
什么都不返回。
You need to add this statement to the function您需要将此语句添加到函数中
return sum / n;
And the first parameter shall have an integer type instead of the type float
.并且第一个参数应具有整数类型而不是
float
类型。
float Findaverage(float n,float numbers[]) {
^^^^^
Secondly in this call of the function其次在这个函数调用中
average = Findaverage(50,numbers[50]);
the argument numbers[50]
having the type float
instead of the type float *
is invalid.具有类型
float
而不是类型float *
的参数numbers[50]
无效。 You need to write你需要写
average = Findaverage(50,numbers);
The function can be declared and defined the following way可以通过以下方式声明和定义该函数
double Findaverage( const float numbers[], size_t n )
{
double sum = 0.0;
for ( size_t i = 0; i < n; i++ )
{
sum += numbers[i];
}
return n == 0 ? 0.0 : sum / n;
}
And the function can be called like该函数可以像这样调用
double average = Findaverage( numbers, sizeof( numbers ) / sizeof( *numbers ) );
Change改变
average = Findaverage(50,numbers[50]);
to到
average = Findaverage(50,numbers);
numbers[50]
refers to a single array element, not the entire array. numbers[50]
指的是单个数组元素,而不是整个数组。 It's also one past the end of your array (which is indexed from 0
to 49
).它也是数组末尾的一个(索引从
0
到49
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.