summation of square and square root of specific rows and column in 2 dimensional array?

2012-12-21 9:51 am
Given the floating point array x[10][10] with initial values,
find the sum of all
• The square of the numbers in the even rows (i.e., rows 2,4,6,8,10)
• The square root of the numbers in the odd(ie column 1,3,5,7,9)

below are the code i've manage so far...

#include <iostream>
#include <cmath>

using namespace std;

int main()
{

float x[10][10] = {{1,2,3,4,5,6,7,8,9,0},{13,14,18,19,8,5,6,3,4,2},{8,7,6,4,1,2,3,5,2,8},{11,12,13,14,15,16,17,18,19,20},{-5,-7,-66,-38,7,1,9,44,6,-2},{0,4,7,-3,6,1,8,-3,6,8},{-1,2,-3,4,-5,6,-7,-8,-9,10},{56,9,0,0,3,5,1,-4,-6,3},{2,1,5,-7,4,-6,3,9,0,5},{2,5,67,4,7,8,1,-7,0,6}};
float ev[5][10];
float od[10][5];
int y = 0;
float z = 0;

cout << "For the data inside the program.\n";
for(int i=0; i<10; i++)
{for(int j=0; j<10; j++)
cout << x[i][j] << " ";
}

for (int i = 0; i < 10; i+=2)
{for (int j = 0; j < 10; j++)
{y = pow(x[i][j],2);
ev[5][10] = y;
// dunno how to continue
}
}

cout << "The square of the even row = " << sum_ev
;

for (int j = 0; j < 10; j+=2)
{for (int i = 0; i < 10; i++)
{z = sqrt(x[i][j]);
od[5][10] = z;
// dunno how to continue
}
}

cout << "The square root of the odd column= " << sum_od ;

回答 (1)

2012-12-21 10:00 am
✔ 最佳答案
there's no reason to make additional arrays, infact that adds a lot more complexity and makes it more difficult
all you need is the original 10x10 array

and you've already solved both problems pretty much

//square of numbers in the even rows
for (int j = 0; j < 10; j+=2){
for (int i = 0; i < 10; i++){
cout << pow(x[i][j],2) << ' ';
}
}

edit: Oh, it wants the SUM of all those numbers, in that case the above code is step 1, here's step 2


int sum = 0; //create variable to hold the sum
//square of numbers in the even rows
for (int j = 0; j < 10; j+=2){
for (int i = 0; i < 10; i++){
sum += pow(x[i][j],2);
}
}
//output the sum
cout << "sum of the squares = " << sum;


收錄日期: 2021-05-03 14:28:13
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20121221015150AAvCOyL

檢視 Wayback Machine 備份