简体   繁体   English

浮动不返回SharedPreferences

[英]float doesn't return in SharedPreferences

Why float doesn't return the wanted value in another activity. 为什么float在另一个活动中不返回想要的值。 All the other ints, and Strings does, but float doesn't. 所有其他int和Strings都有,而float却没有。

Sender activity: 发件人活动:

 SharedPreferences prefs = this.getSharedPreferences(
                        "details", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = prefs.edit();
                edit.putInt("weight", weight);
                edit.putInt("height", height);
                edit.putInt("age", ag);
                edit.commit();

Log.d("BMI Height" , String.valueOf(height));
Log.d("BMI Weight" , String.valueOf(weight));

BMI Height and weight in the console are the correct BMI控制台中的身高和体重正确

Receiver activity: 接收者活动:

 SharedPreferences prefs = getSharedPreferences(
            "details", Context.MODE_PRIVATE);

    int age=prefs.getInt("age", Integer.parseInt("16"));
    int weight=prefs.getInt("weight", Integer.parseInt("50"));
    int height=prefs.getInt("height", Integer.parseInt("165"));

Log.d("BMI Height" , String.valueOf(height));
Log.d("BMI Weight" , String.valueOf(weight));

    float formula = weight / (height * height) * 10000;

    Log.d("BMI Formula", String.valueOf(formula));

BMI Height and weight in the console are the still correct, but formula returns 0.0 in the console. BMI控制台中的身高和体重仍然正确,但是公式在控制台中返回0.0。

Because you're doing math on integers and storing the result in a float. 因为您正在对整数进行数学运算并将结果存储在浮点数中。 The math is still done on integers. 数学仍然以整数完成。 So you'll divide weight (50) by height*height (around 10K). 因此,您将体重(50)除以身高*身高(约10K)。 THat's less than 1, but the result of dividing two integers is always an integer. THat小于1,但将两个整数相除的结果始终是整数。 So it rounds to 0. 因此它舍入为0。

To fix that, make weight and height floats. 要解决此问题,请使体重和身高浮动。

try like this 这样尝试

edit.putFloat("key", (float) 10.10);

and try to get the value 并尝试获得价值

prefs.getFloat("key", (float) 10.0);

since weight and height are integers so probably the result should be zero. 由于体重和身高是整数,因此结果应该为零。 For example 例如

int a = 10
int b = 5

float c = a/(b*b);

it will return 0 because calculation in int results 0 and then it will typecast into float 0.0 you can typecast weight and height to float like 它将返回0,因为int中的计算结果为0,然后它将类型转换为float 0.0,您可以将重量和高度类型转换为float

float c = (float)a/((float)b*(float)b);

then it will return you 0.400 那么它将返回您0.400

The problem here is you are dividing ints, the result is then automatically cast to float, So if the result isn't great enough you get 0 (and either way you'd get an int). 这里的问题是您正在分割整数,然后将结果自动强制转换为浮点数,因此,如果结果不够好,您将获得0(或者以任何一种方式获得一个整数)。

You have to cast the first int in the division to float to get the desired result. 您必须将除法运算中的第一个int进行浮点运算才能获得所需的结果。

float formula = (float) weight / (height * height) * 10000;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM