gpt4 book ai didi

c - 函数无法正确添加二维数组的元素?

转载 作者:行者123 更新时间:2023-11-30 15:02:22 25 4
gpt4 key购买 nike

这里我有一个程序,提示用户输入 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]);
}
}

最佳答案

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

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]);
}
}

关于c - 函数无法正确添加二维数组的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41080941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com