when i use following code i do not get correct output:
In this the function maxHeartRate returns an Integer value.Lets take it equal to 199.

public String targetHeartRate()
    {
       double a = maxHeartRate()/2;
       double b = ((85/100)*(maxHeartRate())); 
       String c = a+"-"+b;
       return c; 
    }

Using above code i get String c as :99.0-0.0
But when i change

double b = ((85/100)*(maxHeartRate()));

to

double b = ((85*maxHeartRate())/100);

i get the correct output.
Then String c becomes:99.0-169.0
My question is why i am not getting the correct output even though both should evaluate to the same value?

Also i am not able to post correctly in this forum, i put my code snippet in the code section then also it gives me error like:
The code snippet in your post is formatted incorrectly. Please use the Code button in the editor toolbar when posting whitespace-sensitive text.

Edited 4 Years Ago by hszforu

ok,i can post correctly to the forum now.

Also i am not able to post correctly in this forum, i put my code snippet in the code section then also it gives me error like:
The code snippet in your post is formatted incorrectly. Please use the Code button in the editor toolbar when posting whitespace-sensitive text

Edited 4 Years Ago by hszforu

When you have an arithmetic expression with all integers, Java does integer arithmetic.
The integer result of 85/100 is 0 (fractions are truncated)
That's why you get 0 if you do the division first. If you do the multiplication first it's OK.

Ok got it, both the statements are working now if change 85 to 85.0 and and 100 to 100.0

When you have an arithmetic expression with all integers, Java does integer arithmetic.
The integer result of 85/100 is 0 (fractions are truncated)
That's why you get 0 if you do the division first. If you do the multiplication first it's OK.

Yes, if you change any one of the values for an operator to float then the operation will be done in float. But be careful - if the final result is an int then you can get weird rounding/truncation problems by switching into float and out again, so sometimes your result is + or - 1 from the result you expect.
In general its better to keep everything integer, and re-arrange your formula to do the multiplications first and the divisions last. The results from this are 100% predicatable.

Edited 4 Years Ago by JamesCherrill

This question has already been answered. Start a new discussion instead.