C나 C++의 double 자료형에 대한 간단한 질문입니다.

dgsquare의 이미지

안녕하세요. 다름이 아니라 C++에서 double형을 int형으로 casting해서 사용할려고 하는데,
제가 배운바에 의하면 소숫점이 절삭된다고 알고 있거든요.
근데 프로그램을 짜다가 오차가 계속 생겨서 디버깅을 하다가 다음 현상을 발견했습니다.

#include
#include
using namespace std;

int main(void) {
double dt = 15.25-14.74;

cout << floor(dt * 100.0) << endl;
cout << (int)(dt * 100.0) << endl;

cout << floor(dt * 100.0+0.5) << endl;
cout << (int)(dt * 100.0+0.5) << endl;

return 0;
}

실행하면 결과가
50
50
51
51
로 나옵니다.
아래 2개는 다른 분들이 만든 코드를 보고서 시도해 본것이구여.
문제는 위의 2개의 결과인데, dt값이 0.51이기 때문에 *100하면 51이되어서 51이 출력될 줄 알았는데 50이 출력되네여. 참고로 casting을 하지 않으면 51이 나옵니다.
모든수가 그런거는 아니고.. 몇몇수가 그러네여.

부동소숫점과 관련해서 제가 너무 무지한지라 조언 바랍니다. 아래 2줄처럼 쓰면 된다고는 하는데 왜그런지 모르겠네요..

sephiron의 이미지

dt 값이 0.51이 아닌 0.509xx 등등이 될 수 있습니다.
부동소수점 표현법은 근사치로만 사용할 수 있기 때문입니다. dt 값을 %f 로 출력해 보시죠.
----
Forensic Computing On Linux

아직 멀었어

dgsquare의 이미지

sephiron님 말대로 0.59999999999999979 가 나오네여-_-;
단순 %f로 하니 6자리밖에 안나와서 %.20f로 하니 저수가 찍혀버리네여.
casting하면서 약간의 숫자를 오차범위내에서 약간의 숫자를 더해주는게 필요하다는 것을 알았습니다.
참고로 printf가 해당 소수점 자릿수까지 출력시 한자리 아랫수를 반올림해서 보여준다는 것도 이제야 알았습니다.

l0v2nara의 이미지

floor는 뭐죠..^^::

첨보는 명령어네..;;

cppig1995의 이미지

floor는 가장 가깝고 작은 정수(3.7 -> 3)
ceil은 가장 가깝고 큰 정수(3.4 -> 4)
를 찾는 함수로, math.h에 정의되어 있습니다.

Real programmers /* don't */ comment their code.
If it was hard to write, it should be /* hard to */ read.

ssehoony의 이미지

floor 은 소수 첫째 자리에서 내림
ceil 은 소수 첫째 자리에서 올림
round 은 소수 첫째 자리에서 반올림

round 는 ansi c 에는 아마 없는 함수죠? (보통 다른 언어에는 있습니다. ^^)

vacancy의 이미지

언어에 따라 round는
banker's round로 구현되는 경우가 있으니
주의해야합니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.