1

The question:

Input data will give the number of test-cases in the first line. Then test-cases themselves will follow, one case per line. Each test-case describes an array of positive integers with value of 0 marking end. (this zero should not be included into calculations!!!). Answer should contain average values for each array, rounded to nearest integer (see task on rounding), separated by spaces.

Problem:

Works fine but at third indice sum is assigned value of arrayInput and it messes everything up. Why does this happen and how can I fix it?

 //araytest #include<cmath> #include<iostream> using namespace std; int main() { //var int i = 0; int array[13] = {}; //take in # arrays cin >> i; for(int x = 0; x<i; x++ ) { //reset variables (for every array) float arraySize = 0, sum = 0, avg = 0; int indice = 0, arrayInput = 0; while(cin >> arrayInput){ if(arrayInput == 0) { if(indice == 0) { arraySize = 1; /*if only 0 put in first indice to prevent divide by 0 */ break; } else { arraySize = indice; // 0 doesn't count break; } } sum += arrayInput; array[indice] = arrayInput; arrayInput = 0; indice++; } avg = round(sum/arraySize); cout << avg << " "; } return 0; } 
3
  • 2
    You have 0-sized array, and later you're assigning to non-existing elements of it. that's UB. Commented Oct 8, 2016 at 15:27
  • Array size is zero. Give it a size. Or use vector Commented Oct 8, 2016 at 15:27
  • And, in addition to all of the above, neither an array, nor a vector, is needed. This can be accomplished without using an array or a vector, and I suspect that if you hand in something cobbled together with a help of a vector or an array, you will fail this assignment. Commented Oct 8, 2016 at 15:29

1 Answer 1

1

First, like other people said, the array you used in this code is totally useless. It did nothing but save arrayinput.

Second, you let arraysize sum avg to be type float. However, arrayinput is assigned to be integer!! That means you never get result like this 2.xxx. So the type you declare for variables is meaningless. They should have same type declaration. I don't understand why you code does not work well. Because if you enter integer number, you wont get anything wrong. But it will crash if you give number like 2.xxx or x.xxx.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.