我有三个整数数组。 SIZE 为 365。
double month[SIZE], day[SIZE];
int countMonths[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
在 Month 数组中,我想填充月份的 int 值 - 对于前 31 个字段将有一个 1,接下来的 28 个字段将有一个 2,等等。对于该月的天数。
month[0-31] 的值为 1(对应于第 1 个月) month[32-60] 会取值2(对应月2)
我的循环不工作。外循环将循环遍历数组中的 365 个项目。我希望内部循环循环 - 对应于 countMonths[1] 等中的值的数量;
for (int i = 0; i < SIZE; i++)
for(int j = 1; j < countMonths[j]; j++)
month[i] = i+1;
我想做的第二个查询是使用相同的 countMonths 内循环来进行更新,而不是将所有值都设为 1(对应的月份 1)。它将放置 1、2、3 等,直到达到 31,然后再次从 1 开始。
for (int i = 0; i < SIZE; i++)
for(int j = 1; j < countMonths[j]; j++)
day[i] = j;
两个查询都没有做我想做的...请指教。 使用以下逻辑,我似乎在每个月的第一天进行更新和循环。
int i = 0;
int currentmonth = 0;
int currentday = 1;
while(i < SIZE && i < countMonths[currentmonth])
{
month[i] = currentmonth+1;
day[i] = currentday;
i++;
currentday++;
if(currentday > countMonths[currentmonth]);
{
currentmonth++;
currentday = 1;
}
}
最佳答案
您在 2 个循环中使用 2 个索引,而在 1 个循环中使用 3 个索引会更有用:
currentDay = currentMonth = 1
while(destinationIndex and currentMonth are valid indexes)
assign current day and month to destination arrays
increment destinationIndex and currentDay
if(currentDay is greater than possible for currentMonth)
increment currentMonth
set currentDay back to 1
关于c - 递增嵌套数组 - 带有日期信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26397231/