14

在我的数据库中,我有几个“真实”字段。

继承人的结构:

    database.execSQL("create table " + TABLE_LOGS + " (" 
            + COLUMN_ID + " integer primary key autoincrement," 
            + COLUMN_ID_DAY_EXERCISE + " integer not null,"
            + COLUMN_REPS + " integer not null"
            + COLUMN_WEIGHT + " real not null"
            + COLUMN_1RM + " real not null"
            + COLUMN_DATE + " integer not null"
            + ")");

现在我要做的是计算 1RM 以便我可以将其插入数据库。

到目前为止,这是我的功能:

public void createLog(long id_day_exercise, float reps, long weight) {

    // create 1rm
    // create date timestamp

    float onerm = weight/(1.0278-(.0278*reps));
    long unixTime = System.currentTimeMillis() / 1000L;
}

我被困在这里。它给了我错误“无法从双精度转换为浮点数” onerm。我尝试通过在它前面使用 (Float) 将重量转换为浮点数,我尝试使用 weight.floatValue() 并且似乎没有任何效果。

4

5 回答 5

31

你试过这个吗?

float onerm = (float) (weigth/(1.0278-(.0278*reps)));
于 2013-01-25T00:57:00.170 回答
15

这种方法怎么样?

Float.valueOf(String.valueOf(your_double_variable));
于 2014-11-02T00:19:35.673 回答
10

从 double 转换为 float 可以这样完成:

double d = 1.2;
float f = (float) d;

或者,如果您只需要以1.2浮点数开头,则使用1.2f.

笔记

  • float是单精度 32 位和double双精度 64 位,因此在转换中可能会丢失精度。请参阅原始数据类型文档
于 2017-01-31T08:40:00.240 回答
3

在我的情况下,你有一个Double变量,你可以Double.floatValue()这样调用:

Double deg = 45.0d;
float floatDeg = deg.floatValue();
于 2018-08-12T20:01:54.660 回答
2

问题是该double类型的精度高于float. 进行该分配时,您将丢失信息。这就是编译器不允许你这样做的原因。这类似于当你想做char b = awhere a is an时发生的事情int

使用显式转换可能允许您进行编译,但可能会发生数据/精度损失。

编辑:

由于在您的原始问题中,计算的所有输入都是floats,因此请使用浮点文字。例如,1.0278是一个双字面量。即附加f到常量,以便所有计算都是浮点数并且不提升为双精度数:

float onerm = weight/(1.0278f-(.0278f*reps));
于 2013-01-25T01:03:52.013 回答