java - 百分比计算在 Java 中给我零

标签 java typecasting-operator

我的代码:
long totalVolume = sellVolume + buyVolume; float sellPercent = (float)(sellVolume/totalVolume); float buyPercent = (float)(buyVolume/totalVolume);

第一行代码中的所有变量都很长,然后我试图计算它的百分比....但 java 只返回零... 为什么会这样——我是不是在打字时做错了什么

最佳答案

为了执行浮点除法(而不是长除法),您应该在执行除法之前将其中一个操作数转换为 float

float sellPercent = (float)sellVolume / totalVolume;
float buyPercent = (float)buyVolume / totalVolume;

关于java - 百分比计算在 Java 中给我零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35981711/

相关文章:

java - 重写 System.out.print 语句更容易一些

c - "cast specifies a conversion"是什么意思?

PHP 类型转换 null 或 int

java - 在 Java 8 中的 Map<String, List> 中向 List 添加值

C++:类型转换运算符重载 - Visual Studio 2013 内部错误

c++ - 尝试将整数强制转换为 void 以按值传递给 pthread 函数

c++ - 类型转换问题 : Returning as integer instead of float/type

java - Hadoop Yarn运行时异常

java - 无法序列化 HashMap

java - HttpClient:HttpGet 方法失败: HTTP/1.0 503 服务不可用