整数之间的计算

Calculations between integers

我正在尝试计算喜欢和不喜欢的两个整数之间的比率。它似乎返回 0 而不是我应该在我的计算器中得到的数字。我做错了什么?

int likes = 200;
int dislikes = 100;
float ratio = (likes / 2000) * ((likes / likes) + dislikes) * 100;

整数不能表示分数,这就是使它们成为整数的原因。用整数除法会丢弃余数,因此,如果您尝试将一个较小的整数除以一个较大的整数,您将得到 0。您在尝试将它们转换为浮点数的过程中走在正确的轨道上,但是您当前的实现对转换前的整数值。在进行计算之前,您需要将 likesdislikes 转换为 float 值。

变化:

int likes = 200;
int dislikes = 100;
float ratio = (likes / 2000) * ((likes / likes) + dislikes) * 100;

至:

float likes = 200;
float dislikes = 100;
float ratio = (likes / 2000) * ((likes / likes) + dislikes) * 100;

或者像这样在除法之前施法

int likes = 200;
int dislikes = 100;
float ratio = ((float)likes / 2000) * (((float)likes / likes) + dislikes) * 100;

已更新:修复了评论中指出的拼写错误