为什么我的分区结果似乎已关闭?

时间:2011-10-19 03:30:37

标签: c++ c

我无法理解为什么我的部门的结果会向下舍入?

#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 ++程序中打印%值?

感谢。

2 个答案:

答案 0 :(得分:4)

这是因为你正在进行整数除法。 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);

答案 1 :(得分:1)

因为你首先将它们归零:)

为每个百分比

执行此操作
dPercent = ((dTotal*100)/total);