# Thread: int will work, but double/float wont?

1. ## int will work, but double/float wont?

I've been working on an assignment, and it didnt take very long, but there is one slight error thats getting me completely frustrated...I want to use a double or float for 2 of the variables, so that it doesnt truncate when it calculates the average and standard deviation of a set of numbers, but average always comes out as 0 when its a double/float, and will come out just fine when its an int (except for the truncation)....does anyone see anything wrong with my code, and any help would be appreciated

Project Folder

2. Post a snippet of code here, I for one have no way of opening a rar file on my current PC.

Code:
```public:
int m_Sum;
int m_Size;
void StdDev (void);
void Display (CDC* pDC, int ww, int wh, int DispControl);
void Initialize (void);
double m_Std;
double m_Average;
int m_Minimum;
int m_Maximum;
int  m_Array[1000];```
cpp file
[code]
void C1DArray::Initialize()
{
m_Sum = 0;

srand(time(NULL));

int tmax = 0, tmin = 32768;

for (int i = 0; i < m_Size; i++)
{
m_Array[i] = rand();

if (m_Array[i] > tmax)
{
m_Maximum = m_Array[i];
tmax = m_Maximum;
}

if (m_Array[i] < tmin)
{
m_Minimum = m_Array[i];
tmin = m_Minimum;
}

m_Sum += m_Array[i];
}

m_Average = m_Sum / m_Size;

}

the output
Code:
```case 4:		{
x = (ww - (15*7)) / 2;
y = (wh) / 2;
sprintf(buffer, "Average = %d", m_Average);
pDC -> TextOut (x, y, buffer);
break;
}```
if i output sum, its fine, if i output m_size, its fine....however, when i outputaverage its 0 when double, and perfect when int (except for the truncation which isnt exceptable )

4. >>m_Average = m_Sum / m_Size;
Both m_Sum and m_Size are ints so, you need to cast them to make the divide keep the precision.

>>sprintf(buffer, "Average = %d", m_Average);
Try using %f instead of %d

If you can't get it going, try breaking it down to a small program like this:
Code:
```#include <stdio.h>

int main(void)
{
int i1 = 10, i2 = 3;
double f = (double)i1 / i2 ;

printf ("%f\n", f);

return 0;
}```

5. type casting didnt seem to work....it did the same thing if i would orginally declare sum as a double....any other suggestions?

edit, the %f in the printf statement did the trick...however, one last problem (ive never used printf before this, so im not sure how formatting is), but the output comes out with a precision of 6 decimal points...how can i have it so it only shows 2 or 3?

again, thank you so much

6. >>> have it so it only shows 2 or 3?

%.nf where n is the desired precision, eg. %.2f for two places.

7. thank you very much