C++Builder Programming Forum
C++Builder  |  Delphi  |  FireMonkey  |  C/C++  |  Free Pascal  |  Firebird
볼랜드포럼 BorlandForum
 경고! 게시물 작성자의 사전 허락없는 메일주소 추출행위 절대 금지
C++빌더 포럼
Q & A
FAQ
팁&트릭
강좌/문서
자료실
컴포넌트/라이브러리
메신저 프로젝트
볼랜드포럼 홈
헤드라인 뉴스
IT 뉴스
공지사항
자유게시판
해피 브레이크
공동 프로젝트
구인/구직
회원 장터
건의사항
운영진 게시판
회원 메뉴
북마크
볼랜드포럼 광고 모집

C++빌더 Q&A
C++Builder Programming Q&A
[46078] 정밀도 문제.
BloodWolf [cyberpd] 1073 읽음    2006-08-08 10:20
하드웨어 장비로부터 온도값을 얻어와 변환하는 함수를 만들고 있는데,
double에서 unsigned short 형으로의 변환중에 정밀도 문제가 발생하네요.

temperature_to_value() 함수는 바로 변환한 것이고, 변환시 오류가 발생합니다.
temperature_to_value2() 함수는 double에 10을 곱한 후,
unsigned short 형에서 10을 나눈것으로 정상적으로 변환이 됩니다.

정밀도 문제를 해결하기 위해서 이러한 방법뿐이 없는것인가요?

const double to_temperature(const unsigned short _value)
{
    try
    {
        if(_value>0x0FFF) return 0xFFFF;
        return ((((double)(_value&0x0FFF))*0.05)-125.0);
    } catch(...)
    {
        return 0xFFFF;
    }
}
//---------------------------------------------------------------------------

const unsigned short temperature_to_value(double _temperature)
{
    try
    {
        if(_temperature==(double)0xFFFF) return 0xFFFF;
        _temperature=(_temperature+125.0)*20.0;
        unsigned short value=std::ceil(_temperature);
        return value;
    } catch(...)
    {
        return 0xFFFF;
    }
}
//---------------------------------------------------------------------------

const unsigned short temperature_to_value2(double _temperature)
{
    try
    {
        if(_temperature==(double)0xFFFF) return 0xFFFF;
        _temperature=(_temperature+125.0)*20.0;
        unsigned short value=std::ceil(_temperature*10.0);
        value/=10.0;
        return value;
    } catch(...)
    {
        return 0xFFFF;
    }
}
//---------------------------------------------------------------------------

void test(void)
{
    std::fstream file("temperature.txt",std::ios_base::out);
    for(unsigned short index=0x0000; index<=0x0FFF; ++index)
    {
        char buffer[128]={0,};
        double temperature=to_temperature(index);
        unsigned short value=temperature_to_value(temperature);
        std::sprintf(buffer,"[0x%04X] T=%-7.02f, V=0x%04X, %s",
            index, temperature, value, (index==value) ? "E" : "D");
        file << buffer << std::endl;
    }
    file.close();
}

+ -

관련 글 리스트
46078 정밀도 문제. BloodWolf 1073 2006/08/08
46097     Re:정밀도 문제. 1152 2006/08/08
Google
Copyright © 1999-2015, borlandforum.com. All right reserved.