cast variable to int vs round() function

久未见 提交于 2019-12-18 03:49:34

问题


I have seen it in several places where (int)someValue has been inaccurate and instead the problem called for the round() function. What is the difference between the two?

Specifically, if need be, for C99 C. I have also seen the same issue in my programs when writing them in java.


回答1:


In case of casting a float/double value to int, you generally loose the fractional part due to integer truncation.

This is quite different from rounding as we would usually expect, so for instance 2.8 ends up as 2 with integer truncation, just as 2.1 would end up as 2.

Update:

Another source of potential (gross) inaccuracy with casting is due to the limited range of values being able to be represented with integers as opposed to with floating point types (thanks to @R reminding us about this in the comment below)




回答2:


  1. Casting to int truncates a floating-point number, that is, it drops the fractional part.
  2. The round function returns the nearest integer. Halfway cases are rounded away from zero, for example, round(-1.5) is -2 and round(1.5) is 2.

7.12.9.6 The round functions

Synopsis

#include <math.h>
double round(double x);
float roundf(float x);
long double roundl(long double x);

Description

The round functions round their argument to the nearest integer value in floating-point format, rounding halfway cases away from zero, regardless of the current rounding direction.

Returns

The round functions return the rounded integer value.

Source: the C99 standard (ISO/IEC 9899:1999). This section did not change in the C11 standard (ISO/IEC 9899:2011).

(For those who are interested, here is a clear introduction to rounding algorithms.)




回答3:


Specifically for C, it is (probably) true in most cases that casting truncates, however, you should always test the outcome to be sure.

The problem with casting is, that it can EITHER truncate OR round. What it does depends largely on the programming language, marginally on the specific compiler used. Which means there is no general rule for the outcome that will always apply.

Round() is universally used to generate a result similar to mathmatical rounding. There is an edge case that needs to be specifically monitored for .5, which sometimes rounds to the next even number.



来源:https://stackoverflow.com/questions/11128741/cast-variable-to-int-vs-round-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!