gpt4 book ai didi

c - 如何在给定的迭代次数后清除总和的值?

转载 作者:太空宇宙 更新时间:2023-11-04 00:59:42 24 4
gpt4 key购买 nike

<分区>

请原谅我的措辞,因为我正在努力正确地描述这个问题。

我正在开发一个程序来创建多年的月度降雨量摘要。现在,该程序在 5 年内循环 12 个月,并将打印结果。

不幸的是,我无法弄清楚如何正确计算年度总数。例如:如果我为前 12 个值(即第 1 年)输入 1,则总数为 12。如果我为第 2 年做同样的事情,则总数变为 24。它 - 看起来 - 好像它正在打印值的总和来自所有年份,而不仅仅是一年内的总和。

这是我所看到的总结版本:

Do you want to input Precipitation data? (y for yes)
y
Enter rain for 1, 1:
1
Enter rain for 1, 2:
1
...
1
Enter rain for 1, 11:
1
Enter rain for 1, 12:
1
Total rainfall: 12.00
Enter rain for 2, 1:
1
Enter rain for 2, 2:
1
...
Enter rain for 2, 12:
1
Total rainfall: 24.00

当我尝试构建一个单独的循环时,例如下面的循环,值始终为 0.00:

void inputdata() {
/* variable definition: */
float Rain = 1.0;
float total = 0.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;
}
printf("Total rainfall: %.2f\t\n", total);
}
for (int month = 0; month < NUMMONTHS; month++) {
total = total + Rain;
}
}

最令人沮丧的是,我几乎可以看到它是如何执行数学运算的,但就是看不到如何修复它们。
这是我的完整代码:

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

// function prototypes
void inputdata();
void printdata();

// Global variables
// These are available to all functions
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 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;
float total = 0.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;
total = total + Rain;
}
printf("Total rainfall: %.2f\t\n", total);
}
}

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

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