Redefender
Redefender

Reputation: 19

array input not working

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;
}

Upvotes: 1

Views: 364

Answers (1)

Fangming John
Fangming John

Reputation: 11

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.

Upvotes: 1

Related Questions