0
這裏我每個月都會提示用戶降雨輸入英寸的5年計劃。該方案有3層主要的功能,inputData
,printData
,並sumRain
。函數不會正確添加2d數組的元素?
我想不通爲什麼我的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]);
}
}
的目的:'如果(enterData ==「Y '){'如果用戶輸入'Y',程序是否應該繼續?建議通過了'enterData通過函數:'CTYPE ... h' – user3629249
調用任何的'的scanf()的時候'家庭的功能,經常檢查返回值(不是:'tolower的()在頭文件'找到參數值),以保證手術成功 – user3629249
寫'float'值有兩個要求。 1)它必須包含一個小數點2)它後面必須緊跟字母'f'。實際上,'1.0'是一個'double'值,爲了使它成爲'float'值,寫爲:'1.0f'。 – user3629249