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

Recommended Answers

All 3 Replies

what is the size? and what kind of numbers are in the array (what does it contain)?

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?

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?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.