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.

Recommended Answers

All 5 Replies

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

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.

Ok i will remember this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.