cout << float; problem

I am just simply trying to output a float with 2 decimal places by adding up a bunch of numbers and finding the average. However, when I cout << avg, the output is a single digit number that is the "floor" of what the actual value should be. example, it inputs 3,5,2,8 to the function and adds them up to 18 then divides by 4 which should give 4.5, but when I do it it only gives me 4. How do I make it so it shows more decimal places? Thanks
At any point in your code, are you dividing an int by another int? If you are, that will give you an int with no decimal places.

For example, 4/3=1 but 4.0/3=1.3333333333
Last edited on
nope, all of my vars are floats. Here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
{
 srand((unsigned)time(0)); 
 float randNum[10];
 int i;
 float sum=0;
 float avg;
 cout << "Here are 10 random numbers between 1 and 10: "<<endl<<endl;
 for(i=0;i<10;i++)
 {
 randNum[i] = (rand()%10)+1;
 cout << randNum[i] << ", ";
                  }
 cout <<endl<<endl;
 for(i=0;i<10;i++)
 {
  sum += randNum[i];
                  }
  avg = sum/10;
 cout <<sum<< "The average of these numbers is: "<<avg;
 getch();
}
Works OK here: http://www.ideone.com/7SZKk .
it works ok...

Here are 11 random numbers between 1 and 11

1, 3, 3, 10, 10, 8, 1, 6, 3, 1, 2,

48The average of these numbers is: 4.36364
Last edited on
Topic archived. No new replies allowed.