-2

I am having some trouble and I cant really even figure out what is wrong, so I needed some help. I need to take a percentage of a number that one of the structs in my array has, for each one.

my struct looks like

struct person{
    int number;
    string name;
    float share;
}

So I use a for loop to get the total of number, no problem, all comes out good. But when I try to get what percent of the total I always get a zero.

for (int i=0; i<numberOfPersons;i++){
    people[i].share = 100 * ((people[i].number)/totalNumber);
}

I don't understand what is going wrong here but people[i].share always comes out as 0.00 when I cout it.

literally all I do after this is cout it and I get the correct values from number and totalNumber. So I'm like really confused.

If I flip the division problem around I get answers(not the right ones obviously), so I know that there is data in the fields when the for loop runs. But where is it going when I run the equation the way I need to run it?

I tried initializing it and leaving uninitialized, swapping the pointers for ints made inside the loop, and more and I always get the same result.

Please help me understand.

1 Answers1

2

I presume your type of totalnumber is int and person.number is int as well.

For operation between ints, the return value is still int

Expanding people[i].share = 100 * ((people[i].number)/totalNumber);

It would be something like people[i].share = 100 * ( 1/10 );

=> people[i].share = 100 * ( 0 );

=> people[i].share = 0;

So you will get 0 as a result;

To prevent it, cast one of int to float.

people[i].share = 100 * ((static_cast<float>(people[i].number))/totalNumber);

Louis Go
  • 2,213
  • 2
  • 16
  • 29