C++ – Why Do Division Results Appear to Be Off

c++

I cannot understand why the results of my division appear rounded down?

#include <iostream>
#include <stdio.h>
using namespace std;

int rVote, oVote, dVote;
int rTotal, oTotal, dTotal, total;
int rPercent, dPercent, oPercent;

bool loop(char vote){
        switch(toupper(vote)){
                case 'D':
                    dVote = 1;
                    dTotal = dTotal + dVote;
                    return true;
                case 'R':
                    rVote = 1;
                    rTotal = rTotal + rVote;
                    return true;
                case 'O':
                    oVote = 1;
                    oTotal = oTotal + oVote;
                    return true;
                case 'Q':
                    return false;
        }
        return true;
}
int main(){
        char vote;
        do{
                printf("Enter Vote [D/R/O] or Q to quit: ");
                scanf("%c%*c", &vote);
        } while (loop(vote));
        total = dTotal + rTotal + oTotal;
        rPercent = ((rTotal/total)*100);
        dPercent = ((dTotal/total)*100);
        oPercent = ((oTotal/total)*100);
        printf("Democrate total vote %d: %d%%\n", dTotal, dPercent);

        printf("Republican total vote %d: %d%%\n", rTotal, rPercent);

        printf("Other total vote %d: %d%%\n", oTotal, oPercent);
}

Great I am being really dumb….
Why is it that any of my *Percent's not printing the % value in this c/c++ program?

Thanks.

Best Answer

It's because you're doing integer division. Integer division in C/C++ rounds down. So your following code:

    rPercent = ((rTotal/total)*100);
    dPercent = ((dTotal/total)*100);
    oPercent = ((oTotal/total)*100);

is all rounding down to 0.

To fix this, you should cast to a floating-point type:

    rPercent = (int)((double)rTotal/total*100);
    dPercent = (int)((double)dTotal/total*100);
    oPercent = (int)((double)oTotal/total*100);

EDIT:

The code above could give some weird results due to rounding behavior. Perhaps something like this might be more appropriate since it rounds to the nearest %:

    rPercent = (int)((double)rTotal/total*100 + 0.5);
    dPercent = (int)((double)dTotal/total*100 + 0.5);
    oPercent = (int)((double)oTotal/total*100 + 0.5);
Related Question