【问题标题】:cannot convert from double to float无法从 double 转换为 float
【发布时间】:2013-01-08 22:22:33
【问题描述】:

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

结构如下:

    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() 并且似乎没有任何效果。

【问题讨论】:

    标签: android integer division


    【解决方案1】:

    你试过了吗?

    float onerm = (float) (weigth/(1.0278-(.0278*reps)));
    

    【讨论】:

      【解决方案2】:

      这种方法怎么样?

      Float.valueOf(String.valueOf(your_double_variable));
      

      【讨论】:

        【解决方案3】:

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

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

        或者,如果您只需要将1.2 表示为浮点数,则使用1.2f

        注意

        【讨论】:

        • 如果精度损失不是一个因素,这是迄今为止最干净的答案
        【解决方案4】:

        在我的例子中,你有一个Double 变量,你可以像这样调用Double.floatValue()

        Double deg = 45.0d;
        float floatDeg = deg.floatValue();
        

        【讨论】:

          【解决方案5】:

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

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

          编辑:

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

          float onerm = weight/(1.0278f-(.0278f*reps));
          

          【讨论】:

          • 那你建议我做什么?
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-26
          相关资源
          最近更新 更多