简体   繁体   中英

Android Java code is not doing math correctly

I am having a very odd result in my Android program when adding two numbers. It is the test code I am using to find out what is going out:

private static final float yChannel[] = {12.0f, 8.0f, 4.0f, 0};

protected void onCreate(Bundle savedInstanceState) {
    Log.i("Rectangles","y1: " + yChannel[0]+2.0f);
    Log.i("Rectangles","y2: " + yChannel[0]);
}

The LogCat result is:

y1: 12.02.0
y2: 12

I simply don't understand all the variables are float. My code is not working because it is not giving the correct result. I also tried cleaning Eclipse project.

"Rectangles","y1: " + yChannel[0]+2.0f

is string concatenation, as the first operand is the string.

try this

Log.i("Rectangles","y1: " + (yChannel[0]+2.0f));

or

float temp = yChannel[0]+2.0f;
    Log.i("Rectangles","y1: " + temp);

您需要在float计算两边加上括号,因为添加到字符串时参数将被转换为字符串

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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