Java 计算整型数组的总数
我有以下代码:Java 计算整型数组的总数,java,arrays,Java,Arrays,我有以下代码: int sum = 0; for(int i = 0; i < POPULATION_SIZE; i++){ // loop through the population (0-99) for(int j = 0; j < 16; j++){ // loop through the individuals (in this case the cities) sum = COST[j][j+1]; }
int sum = 0;
for(int i = 0; i < POPULATION_SIZE; i++){ // loop through the population (0-99)
for(int j = 0; j < 16; j++){ // loop through the individuals (in this case the cities)
sum = COST[j][j+1];
}
fitness[i] = sum;
}
int和=0;
对于(int i=0;i
我正试图增加所有的成本。总和等于所有元素相加的总和
我面临的问题是,每次循环运行时,sum都被设置为下一个值,与前一个值和当前值的总和相加
从人们的回答来看,我现在可以看出我犯了相当愚蠢的错误。这是一个在你变得过于复杂之前记住基本原理的情况吗?要累积
总和
,请将总和=…
更改为总和+=…
:
sum += COST[j][j+1];
顺便说一句,我不知道您的最终目标,但我想知道您是否也希望将int sum=0
移动到外部for
循环中。
也许不是,这取决于你想做什么,这看起来很可疑,仅此而已,供你考虑。你添加+=此运算符来求和值
int sum = 0;
for(int i = 0; i < POPULATION_SIZE; i++){ // loop through the population (0-99)
for(int j = 0; j < 16; j++){ // loop through the individuals (in this case the cities)
sum += COST[j][j+1];
}
fitness[i] = sum;
}
int和=0;
对于(int i=0;i
如果要将每个值分配给变量,则需要将值添加到该变量中。您可以使用+=
运算符进行此操作
要获得每个总体的总和,您需要在外部循环内初始化变量:
for(int i = 0; i < POPULATION_SIZE; i++){ // loop through the population (0-99)
int sum = 0;
for(int j = 0; j < 16; j++){ // loop through the individuals (in this case the cities)
sum += COST[j][j+1];
}
fitness[i] = sum;
}
for(int i=0;i
注意:我不知道您的数据是如何排列的,但是在COST[j][j+1]
中,您对两个索引都使用变量j
,似乎您应该对其中一个使用I
。a)使用+=
而不是=/code>。b) 发布您如何获取数据(在本例中为成本
和人口规模
),这将有助于您将来的问题(不是由像这样的简单打字错误引起的问题)