double variable type output is always 0 [closed]

匿名 (未验证) 提交于 2019-12-03 02:42:02

问题:

For an assignment I have to create a "rock paper scissor lizard spock" game where I have to output the percentage of the winnings at the end. In the program I calculate the number of games player A and B have won including tie games, the total games played, and the win percentage of each player. All the variables are int except for the percentage which is a double variable type. When I calculate the percentage (games won / total games) I get a 0 as a result. Any ideas why? Sorry I could not provide any code, this is an assignment and I'm not allowed to post it anywhere online.

回答1:

Without seeing code I can't be 100% sure, but my guess is that you're dividing values like this:

int numWins   = /* ... */ int numLosses = /* ... */ double ratio = numWins / numLosses; // <-- Error! 

In C and C++, that last line is a logic error. Although you're storing the result as a double, because you're dividing two ints the division is done as integer division and then stored in a double. C and C++ don't look at the type of the variable you're assigning to when deciding what division to use; the ratio of two ints is always computed using integer division.

To fix this, you can add a cast:

double ratio = (double)numWins / numLosses; 

This casts numWins to a double, which ensures that the division is done as floating-point division because at least one of the operands is a double. That should fix your issue.

Hope this helps!



回答2:

In most programming languages, division between two integers is an integer. Thus, 5 / 10 will give 0, as will 1 / 10 and 9 / 10. This takes place before assignment to the result variable, so the fact that the result variable is a double is irrelevant. You need to turn either the divisor or the dividend into a double for the floating point calculation to kick in.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!