0

Hello, for some reason, I am getting a very weird negative nuber as my average for my program, here is my code:

    int sum, avg;
    sum = 0;
    avg = 0;

    for(int i = 1; i < size; i++){
        sum += array[i];
    }
    avg = sum / size;

my output is :-6.84941e+061

3
Contributors
3
Replies
13
Views
4 Years
Discussion Span
Last Post by vmanes
0

here if the contents are weird (if negative decimal values are weird for your program), a basic average returns negative numbers like that:
(python in case you hadn't heard)

import random
def build_array(length = 56, possible_contents = [1,2,0]):
    n = []
    for i in range(0, length):
        n.append(possible_contents[random.randint(0,len(possible_contents) -1)])
    return n

def get_avg(num_list):
    return float(float(sum(num_list)) / len(num_list))

# ran in IDLE:
>>> get_avg(build_array(999, [-0.000027, -0.0000000001, 0]))
# returns:
-8.973005805805728e-06

The size was 999, array contents were a random mix of -0.000027, -0.0000000001, and 0.
So 999 negative decimal values averaged out, gives us a result like that.
Hince the question: What was the size, and what did the array contain?

Edited by chriswelborn: defined 'weird' in better context, explained 'array' contents.

0

Without seeing the rest of the code, it's hard to find your problem.

Is the array actually filled with valid data? What you show appears to be all integer arithmetic, so how does a floating point value come about?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.