我在 C 中創建了一個頭檔案,并將其命名為 statistic.h。我創建了一個函式來計算平均值(我稱該函式為“平均值”)。但是當我使用公式: sizeof (list)/sizeof (list[0]) 時,結果是錯誤的。
頭檔案如下:
#ifndef STATISTIC_H_INCLUDED
#define STATISTIC_H_INCLUDED
float average(int list[]){
int i;
float sum_elements,mean;
int total =sizeof (list)/sizeof (list[0]);
for (i=0;i<total;i ){
sum_elements=sum_elements list[i];
}
mean = sum_elements / total;
return mean;
}
#endif // STATISTIC_H_INCLUDED
//see main code below where I'm trying to call the function I have previously created in the header.
#include <stdio.h>
#include "statistic.h"
int main(){
int list[]={26,12,16,56,112,24};
float mean=average(list); // I'm calling the average function I created in my header
printf("%f",mean);
return 0;
/*The average is 41.00 but I'm getting 19.00 instead . If I don't use
the sizeof function and manually declare the variable total=6 (the
number of element in the list), it gives me the correct result
(41.00).*/
uj5u.com熱心網友回復:
sizeof (list)/sizeof (list[0]);inaverage不起作用,因為它list會衰減為int*作為引數傳遞給函式的時間。您需要將串列的大小作為引數發送到函式中。
例子:
#include <stddef.h>
#include <stdio.h>
float average(int list[], size_t total) { // send total in as an argument
float sum_elements = 0; // note: initialize sum_elements
for (size_t i = 0; i < total; i ) {
sum_elements = sum_elements list[i];
}
return sum_elements / total;
}
int main() {
int list[] = {26, 12, 16, 56, 112, 24};
// do the size calculation here, where `list` is defined instead:
float mean = average(list, sizeof list / sizeof *list);
printf("%f", mean);
return 0;
}
演示
uj5u.com熱心網友回復:
函式中的list引數average不是陣列,而是指標,所以這個sizeof技巧不起作用。
除非它是sizeof或 一元運算&符的運算元,或者是用于在宣告中初始化字符陣列的字串文字,否則型別為“N 元素陣列”的運算式T將被轉換或“衰減”為型別為“的運算式”指向T" 的指標,其值將是陣列中第一個元素的地址。
當你打電話時 average:
float mean=average(list);
運算式list從“6元素陣列int”型別轉換為“指向int”型別,運算式的值與 相同&list[0],因此average實際接收的是指標值,而不是陣列。
在函式引數宣告的背景關系中,T a[N]并且T a[]都“調整”為T *a- 所有三個宣告a為指向 的指標T,而不是T.
您必須將陣列大小作為單獨的引數傳遞:
float average( int *list, size_t list_size )
{
...
for ( size_t i = 0; i < list_size; i )
...
}
并將其稱為
mean = average( list, sizeof list / sizeof list[0] );
您還需要在函式中顯式初始化sum_elementsto 。0average
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/376155.html
上一篇:如何在C 陣列中輸入亂數?
下一篇:在lua中拆分一次函式
