- 1
Array function
I facing a problem which I not sure what my code goes wrong. The question require to use array function and sum 6 integers value (random get the value) and the total must equal to 322. Below is my code. #include <iostream> #include <stdlib.h> #include <cstdlib> using namespace std; int sum(int value[], int j) { int sum = 322; for (int i = 0; i < j; i++) sum += value[i]; return sum; } int main() { int i; int value[ ] = { 0,0,0,0,0,0 }; for (i = 0; i <=5; i++) { value[i] = rand(); } int j = sizeof(value) / sizeof(value[0]); cout << "Total six value are: " << sum(value, j); return 0; }
3 odpowiedzi
+ 1
Let's see
The total must be equal to 322 but the values are initialized by rand() (which returns a int from 0 to RAND_MAX)
So, I don't understand what the question is asking you to do
stdlib.h and cstdlib are the same
sum gives you the sum of 322+sum(value)
You already know the size of value (=6) so just
int value[6];
Or if you want to also initialize them
int value[6]{};
Why declaring i in main if you use it only for the for-loop?
i<6 is better than i<=5
As I said you already know the size of value, const int j = 6 (you could even make it global)
(It would be better putting a endl or a "\n" at the end of that cout)
(You don't need return 0;)
0
Thanks ! The question is generate random 6 numbers and the sum must be 322.
0
Thanks ! :D