函数不能正确添加二维数组的元素?

时间:2016-12-10 22:23:45

标签: c function for-loop multidimensional-array

这里我有一个程序,提示用户每月输入几英寸的降雨量,持续5年。该计划有3个主要功能,inputDataprintDatasumRain

我无法弄清楚为什么我的sumRain函数无法正确计算每年的降雨量总和。

我唯一的猜测是它与不正确的循环使用有关,但我无法肯定地说。由于这是一项家庭作业,因此提示将比实际解决方案更受欢迎。

#define NUMMONTHS 12
#define NUMYEARS 5
#include <stdio.h>

void inputData();
void printData();
void sumRain();

float Raindata [NUMYEARS] [NUMMONTHS];
char years [NUMYEARS] [5] = {"2011", "2012", "2013", "2014", "2015"};
char months [NUMMONTHS] [12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

int main() {
  char enterData = 'y' ; 
  printf("Do you want to enter precipitation data? \n");
  scanf("%c", &enterData);

  if (enterData == 'y') {
    inputData();
    printData();
    sumRain();  
  }
  else {    
    printf("No data was input at this time \n");
  } 
  printf("Please try the precipitation program again. \n");
  return 0;
}

void  inputData() {
  float rain = 1.0;
  for (int year = 0; year < NUMYEARS; year++) {
    for ( int month = 0; month < NUMMONTHS; month++) {
      printf("enter rain for %d, %d: \n", year + 1, month + 1);
      scanf("%f", &rain);
      Raindata [year][month] = rain;
    }
  }
}

void printData() {
  printf("year\t month\t rain\n");
  for (int year = 0; year < NUMYEARS; year++){
    for (int month = 0; month < NUMMONTHS; month++){
      printf("%s \t %s \t %.2f \n", years[year], months[month], Raindata[year][month]);
    }
  }
}

void sumRain() {
  float sums [NUMYEARS] = {0, 0, 0, 0, 0};
  float zero = 0;

  for (int year = 0; year < NUMYEARS; year++){
    for (int month = 0; month < NUMMONTHS; month++){
      sums[year] = zero + Raindata [year][month];
    }
    printf("%s sum is %.2f \n", years[year], sums[year]);
  }
}

1 个答案:

答案 0 :(得分:1)

目前尚不清楚声明变量zero的目的是什么。但无论如何,函数可以按以下方式编写

void sumRain() {
  float sums [NUMYEARS] = {0, 0, 0, 0, 0};

  for (int year = 0; year < NUMYEARS; year++){
    for (int month = 0; month < NUMMONTHS; month++){
      sums[year]  +=  Raindata [year] [month];
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    }
    printf("%s sum is %.2f \n", years[year], sums[year]);
  }
}