# Pfft... I feel like a noob... help?

Printable View

• 02-26-2006
timmygee
Pfft... I feel like a noob... help?
You know how the little programs you do for fun sometimes just leave you tearing your hair out? Here's my broken program - I think it's something to do with undefined floats, but... well you'll have to look. It totals things as 5.2412 exponential to some number, or 2.4359 exponential again and so on... grrr :D

Code:

//program to compute the average of n numbers
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
//greeter
cout << "*****************Compute Averages**********************\n"
<< "**********input a zero to total them all up**********\n";

int num[100], count, total;
int done = 1;
int total_count = 0;  //num[100] is array of the numbers, count current array index
float average;    //the average

for(done = 1; done == 1; total_count++)
{
cout << "Number: ";
cin >> num[total_count];
//if the number does not eq zero, continue
if(num[total_count] == 0)
{
total_count--;
done = 0;
}

}

for(count = 0; count <= total_count; count++)
total += num[count];

average = total/total_count;

cout << "Average: " << average << "\n";

return(0);
}

• 02-26-2006
Salem
Well total isn't initialised before you start adding to it.

Maximise the warnings your compiler can generate.
Code:

\$ g++ -W -Wall -ansi -pedantic -O2 foo.cpp
foo.cpp:6: warning: unused parameter ‘argc’
foo.cpp:6: warning: unused parameter ‘argv’
foo.cpp: In function ‘int main(int, char**)’:
foo.cpp:12: warning: ‘total’ may be used uninitialized in this function

• 02-27-2006
timmygee
Cheers, I'll remember to make g++ more verbose from now on!