我司的结果为什么看起来好象处于关机? [英] Why do my division results appear to be off?
问题描述
我不明白为什么我司的结果出现向下取整?
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);
}
大,我是非常愚蠢的....
为什么说我的任何 *百分比
的不在此C / C ++程序打印%的价值?
Great I am being really dumb....
Why is it that any of my *Percent
's not printing the % value in this c/c++ program?
感谢。
推荐答案
这是因为你做的整数除法。用C整数除法/ C ++几轮下来。所以,你的下面code:
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);
都是四舍五入到0。
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);
编辑:
在code以上可以给由于四舍五入的行为有些怪异的结果。也许因为四舍五入为最接近%,这样的事情可能更合适:
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);
这篇关于我司的结果为什么看起来好象处于关机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!