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?

Mike
  • 662
  • 3
  • 13
  • 27
  • "San Jose-San Francisco-Oakland has the second highest educational-attainment in both bachelor’s and master's degree attainment, and the second highest median household income after Washington-Baltimore-Northern Virginia" Damm you Washington ;) – Byron Whitlock May 05 '10 at 22:42
  • Lol, I hope to take a part of that highest median income when I join the civil service after completing my Computer Science degree. – Mike May 05 '10 at 22:44

1 Answers1

7

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
  • 4,050
  • 1
  • 25
  • 33
  • 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 May 05 '10 at 22:43
  • 1
    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 May 06 '10 at 08:59