所以我得到了一个包含两个数组的代码:一个数组包含三个电影院的售票,另一个包含成人和儿童价格。我的代码分别输出每个影院的总数(3行输出),但我需要那些3的总数。所以不是为cinema1打印828,为cinema2打印644,为cinema3打印1220,我需要打印2692(总共3个电影院)。如何用for循环对3个产品求和?这是代码:
public class Arrays {
public Arrays() {}
public static void main(String[] args) {
float[][] a = new float[][] {{29, 149}, {59, 43}, {147, 11}};
float[] b = new float[] {8, 4};
String[] s = new String[] {"cinema 1", "cinema 2", "cinema 3"};
String[] t = new String[] {"Adults", "Children"};
int i,j;
System.out.println("Cinema Complex Revenue\n\n");
for ( i = 0 ; i <= 2 ; i++ )
{
for ( j = 0 ; j < 1 ; j++ )
{
System.out.println(s[i] + "\t$" +
(a[i][j] * b[j] + a[i][j + 1] * b[j + 1]));
}
}
}
}
输出:1
答案 0 :(得分:3)
只需编码您想要的内容。
int i, j;
float sum = 0;
for (i = 0; i < a.length; i++) {
for (j = 0; j < a[i].length && j < b.length; j++) {
sum += a[i][j] * b[j];
}
}
System.out.println(sum);
或者,如果您只想使用一个for
循环,则可能是
int i;
float sum = 0;
for (i = 0; i < a.length * b.length; i++) {
sum += a[i / b.length][i % b.length] * b[i % b.length];
}
System.out.println(sum);
答案 1 :(得分:1)
您只需要1个嵌套for循环:
Integer totalCost = 0;
for( i = 0 ; i<b.length; i++ ) {
//you should check if the a[i].length == b.length, and throw an exception if not!
for( j = 0 ; j<a.length; j++) {
totalCost += b[i]*a[j][i];
}
}
System.out.println("Total cost: "+totalCost.toString());