我有一个问题,弄清楚我在这里缺少什么。我需要这个程序来总结5年中每一年的降雨量数据。它说我错过了(但不确定在哪里。
感谢代码的帮助:
#define NUMMONTHS 12
#define NUMYEARS 5
#include <stdio.h>
// function prototypes
void inputdata();
void printdata();
// Global variables
// These are available to all functions
float sum=0.0, 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 input Precipatation data? (y for yes)\n");
scanf("%c",&enterData);
if (enterData == 'y') {
// Call Function to Input data
inputdata();
// Call Function to display data
printdata();
}
else {
printf("No data was input at this time\n");
}
printf("Please try the Precipitation program again. \n");
return 0;
}
// function to inputdata
void inputdata() {
/* variable definition: */
float Rain=1.0;
// Input Data
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;
}
}
}
//Computation of total
for (int year=0;year< NUMYEARS; year++) {
for (int month=0; month< NUMMONTHS; month++) {
sum = sum + Raindata[year][month];
}
}
// Function to printdata
void printdata(){
// Print data
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 %5.2f\n", years[year],months[month],Raindata[year][month]);
}
}
//Printing of total
printf("\nsum=%f", sum);
}
这里的任何帮助都会受到赞赏,我正在阅读和研究这个问题,但我找不到类似的例子。
答案 0 :(得分:0)
此代码不是函数的一部分
//Computation of total
for (int year=0;year< NUMYEARS; year++) {
for (int month=0; month< NUMMONTHS; month++) {
sum = sum + Raindata[year][month];
}
}
你想要像
这样的东西void computeTotal() {
//Computation of total
for (int year=0;year< NUMYEARS; year++) {
for (int month=0; month< NUMMONTHS; month++) {
sum = sum + Raindata[year][month];
}
}
}
或将其移至void inputdata()
要获得五个不同的总和,您可以将其分解为五个单独的循环,这些循环对另一个变量求和,或者将总和更改为数组。
float sum[NUMYEARS] = {0.0};
void computeTotal() {
//Computation of total
for (int year=0;year< NUMYEARS; year++) {
for (int month=0; month< NUMMONTHS; month++) {
sum[year] += Raindata[year][month];
}
}
}