What is the meaning of this code [closed]
I found following code in one of the frameworks we are using,
if (nValue + 0.01 > nLimit)
nValue = nValue - 0.01;
if (((nValue+1) / (int)(nValue+1)) == 1)
sprintf(szValue, "%0.0f", nValue);
else
sprintf(szValue, "%0.2f", nValue);
what is the meaning of this code
Assuming the code is dealing with money amounts stored in floats, the first IF is subtracting 1 cent from nValue if that value exceeds a certain limit. I can't say anything about the purpose without more context.
The second chunk deals (awkwardly) with displaying a value without decimal places if it's a straight "Dollar" amount, and other values with two decimal places.
I'd suspect that the first part is a mistaken attempt to ensure nValue does not exceed nLimit. It possibly should be
if (nValue + 0.01 > nLimit)
nValue = nLimit - 0.01;
In other words, if nValue is closer than 0.01 to the limit make it 0.01 less than the limit
To explain how the second part works, it involves dividing a floating point number by the integer part of the number. If the number is an integer then the result will be 1
e.g.
23.00 / 23 = 1 - It's an integer
23.05 / 23 = 1.002 - It's not an integer
Adding 1 to each side is (as ufukgun noticed) to prevent devide by zero, but the devision is redundant as you could simply compare the float with the int
if (nValue == (int)nValue)
The first part tests whether nValue <= (nLimit - 0.01) and then reduces it by 0.01 if this is not the case.
The second part tests to see whether a float value corresponds to an integer and then prints it as an integer if so (e.g. 42
), otherwise prints it with two decimal places (e.g. 42.01
).
if (nValue + 0.01 > nLimit)
nValue = nValue - 0.01;
Without some context it's difficult to understand the purpose of this code. It seems to be trying to ensure that nValue
is at least 0.01 less than nLimit
, but nValue - 0.01
may still be greater than nLimit
and the code doesn't attempt to detect this case. Is nLimit
the maximum value of the type? If not, what is it?
if (((nValue+1) / (int)(nValue+1)) == 1)
sprintf(szValue, "%0.0f", nValue);
else
sprintf(szValue, "%0.2f", nValue);
This is trying to work out if nValue
is a whole number. If it is a whole number, store just the integer portion of the number as a string. Otherwise store the value with two decimal places.
I think nValue is supposed to be greater than 0.
nValue+1 are used for case nValue == 0
if (((nValue+1) / (int)(nValue+1)) == 1)
means nValue is an integer. (like 45.00)
so developer wanted to print different for cases integer and float.
/* min limit of nValue is nLimit */
if (nValue + 0.01 > nLimit) nValue = nValue - 0.01;
/* if nValue is a round number(no floating point value) or zero eg. 4.00 */
if (((nValue+1) / (int)(nValue+1)) == 1)
sprintf(szValue, "%0.0f", nValue);
/* nValue has floating point value eg. 5.002 */
else
sprintf(szValue, "%0.2f", nValue);
Hope this may help you
精彩评论