我不明白为什么我部门的结果会被舍入?

#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);
}

太好了,我真的很笨。。。。
为什么我的任何一个*Percent都不在这个c/c++程序中打印%值?
谢谢。

最佳答案

因为你在做整数除法。C/C++中的整数除法。所以你的代码如下:

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

全部舍入为0。
要解决此问题,应强制转换为浮点类型:
    rPercent = (int)((double)rTotal/total*100);
    dPercent = (int)((double)dTotal/total*100);
    oPercent = (int)((double)oTotal/total*100);

编辑:
由于舍入行为,上面的代码可能会给出一些奇怪的结果。也许这样更合适,因为它可以精确到:
    rPercent = (int)((double)rTotal/total*100 + 0.5);
    dPercent = (int)((double)dTotal/total*100 + 0.5);
    oPercent = (int)((double)oTotal/total*100 + 0.5);

关于c++ - 为什么我的除法结果似乎不正确?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7816244/

10-12 01:41