[英]C warning: excess elements in array initializer and program does not provide expected output
我有以下代碼。 我的計划是計算 2010-2014 年的年總降雨量。 我已經聲明了二維數組。 您可以在代碼片段中看到。但是我每年添加了 12 個月,但編譯器給出了以下警告。 請幫助修復警告和不正確的 output
multi_dimension_array.c:14:54: warning: excess elements in array initializer [-Wexcess-initializers]
{4.3,4.3,4,3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},
第二個問題是它沒有給出預期的 output。
/*
Program name: multi_dimension_array.c
Date: 2022-01-29-23:50:41
*/
#include<stdio.h>
#define MONTHS 12 // number of months in a year
#define YEARS 5 // number of years of data
int main()
{
float sub_total = 0;
float total = 0;
//initializing rainfall data for 2010-2014
float rain[YEARS][MONTHS]=
{
{4.3,4.3,4,3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6}, //warning at this line no.14
{8.5,8.2,1.2,1.6,2.4,0.0,5.2,0.9,0.3,0.9,1.4,7.3},
{9.1,8.5,6.7,4.3,2.1,0.8,0.2,0.2,1.1,2.3,6.1,8.4},
{7.2,9.9,8.4,3.3,1.2,0.8,0.4,0.0,0.6,1.7,4.3,6.2},
{7.6,5.6,3.8,2.8,3.8,0.2,0.0,0.0,0.0,1.3,2.6,5.2}
};
for(int i= 0;i<YEARS;i++)
{
for(int j =0; j<MONTHS;j++)
sub_total += rain[i][j];
printf("%d %f \n", (2010+i),sub_total);
total += sub_total; // total for all years
}
return 0;
}
實際程序 output:
J2V1-MacBook-Air~ # cd "/Users/J2V1/Desktop/coding/c_code/mix/" && gcc multi_dimension_array.c -o multi_dimension_array && "/Users/J2V1/Desktop/coding/c_code/mix/"multi_dimension_array
multi_dimension_array.c:14:54: warning: excess elements in array initializer [-Wexcess-initializers]
{4.3,4.3,4,3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},
^~~
1 warning generated.
2010 28.500002
2011 66.400009
2012 116.200005
2013 160.199997
2014 193.100021
預期 output
2010 32.4
2011 37.9
2012 49.8
2013 44.0
2014 32.9
這個數組聲明
float rain[YEARS][MONTHS]= ...
相當於 vto
float rain[5][12]= ...
也就是說,數組的每個元素都有 12 個子元素。 但是你提供了 13 個初始化器
{4.3,4.3,4,3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},
^^^
初始化列表中似乎有一個錯字,你的意思是
{4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},
^^^
同樣在這個嵌套的for循環中
for(int i= 0;i<YEARS;i++)
{
for(int j =0; j<MONTHS;j++)
sub_total += rain[i][j];
printf("%d %f \n", (2010+i),sub_total);
total += sub_total; // total for all years
}
您需要在外循環中重新分配 sub_total 。 所以循環應該看起來像
for(int i= 0;i<YEARS;i++)
{
sub_total = 0.0f;
for(int j =0; j<MONTHS;j++)
sub_total += rain[i][j];
printf("%d %f \n", (2010+i),sub_total);
total += sub_total; // total for all years
}
注意變量total
的值實際上並沒有被使用。 也許你需要在程序中 output 它。
警告是由於{4.3,4.3,4,3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6}
有 13 個元素而不是預期的 12 個元素。 第三個元素應該是 4.3 而不是 4,3。
編輯:正如@Jonathan 所提到的,在每個元素后使用空格將有助於更容易地發現此類錯誤。
您的第一行包含 13 列,應該是 12。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.