drjun1994 2013-04-23 09:10
浏览 46

投票百分比计算错误[重复]

This question already has an answer here:

I have created a php program where user can can vote on polls and after that, the poll result will displayed with only percentage, however I am facing an error in my program.
Code which I am using for percentage calculation is
<?php echo round(($num_votes / $total_votes) * 100) ?>

Now If we talk about a sample poll result, assume we have five options
option A - 4 votes
option B - 2 votes
option C - 4 votes
option D - 1 votes
option E - 0 votes
Total votes = 11

In this scenario the percentage result generating is
option A - 36%
option B - 18%
option C - 36%
option D - 9%
option E - 0%

But the total of percentage is 99% instead of 100%. What I want is total should always be 100%
Any help would be appreciated
Thanks.

</div>
  • 写回答

4条回答 默认 最新

  • douqiao2471 2013-04-23 09:16
    关注

    If you are working with rounded numbers, you can indeed end up with...rounded numbers. And the sum of those rounded numbers will be different from the regular sum. There's little you can do to change that. If you insist, you'd have to:

    1. calculate the rounded numbers
    2. calculate the sum, and if not 100%,
    3. loop through the rounded numbers and decide which one should get the missing percent.

    But you're messing with the data. You may think you're cleaning it, but you're messing it up.

    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示