views:

69

answers:

1

I have a function that is supposed to calculate the number of times a letter occurs in a sentence, and based on that, calculate the probability of it occurring in the sentence. To accomplish this, I have a sentence:

The Washington Metropolitan Area is the most educated and affluent metropolitan area in the United States.

An array of structures, containing the letter, the number of times it occurs, and the probability of it occurring, with one structure for each letter character and an additional structure for punctuation and spaces:

struct letters
{
  char letter;
  int occur;
  double prob;
}box[53];

This is the function itself:

void probability(letters box[53], int sum
{
     cout<<sum<<endl<<endl;
     for(int c8=0;c8<26;c8++)
     {      
       box[c8].prob = (box[c8].occur/sum);
       cout<<box[c8].letter<<endl;
       cout<<box[c8].occur<<endl;
       cout<<box[c8].prob<<endl<<endl;
     }
}

It correctly identifies that there are 90 letters in the sentence in the first line, prints out the uppercase letter as per the structure in the second line of the for loop, and prints out the number of times it occurs. It continually prints 0 for the probability. What am I doing wrong?

+7  A: 

When you divide occur by sum, you are dividing an int by an int, which truncates (to 0 in this case). It doesn't matter that you are assigning the result to a double. To fix this, cast occur to a double before the division:

box[c8].prob = ((double)box[c8].occur)/sum;
tloflin
Ah, I thought it might have something to do with the math, but I wasn't sure exactly what to change. That fixed it. Thanks.
Mike
A more efficient alternative would be to pass `sum` as a double argument. With this fix, `int sum` is cast to double on each iteration.
MSalters
@MSalters, good point.
tloflin