Changeset 1667


Ignore:
Timestamp:
Jul 26, 2012, 8:22:36 AM (11 years ago)
Author:
sam
Message:

math: add an sprintf() method to real numbers, and ensure they are always
fully initialised.

Location:
trunk/src
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/lol/math/real.h

    r1382 r1667  
    125125    void hexprint() const;
    126126    void print(int ndigits = 150) const;
     127    void sprintf(char *str, int ndigits = 150) const;
    127128
    128129    /* Additional operators using base C++ types */
  • trunk/src/math/real.cpp

    r1513 r1667  
    4141{
    4242    m_mantissa = new uint32_t[BIGITS];
     43    memset(m_mantissa, 0, BIGITS * sizeof(uint32_t));
    4344    m_signexp = 0;
    4445}
     
    12981299template<> void real::hexprint() const
    12991300{
    1300     printf("%08x", m_signexp);
     1301    std::printf("%08x", m_signexp);
    13011302    for (int i = 0; i < BIGITS; i++)
    1302         printf(" %08x", m_mantissa[i]);
    1303     printf("\n");
    1304 }
     1303        std::printf(" %08x", m_mantissa[i]);
     1304    std::printf("\n");
     1305}
     1306
     1307template<> void real::sprintf(char *str, int ndigits) const;
    13051308
    13061309template<> void real::print(int ndigits) const
    13071310{
     1311    char *buf = new char[ndigits + 32 + 10];
     1312    real::sprintf(buf, ndigits);
     1313    std::printf("%s\n", buf);
     1314    delete[] buf;
     1315}
     1316
     1317template<> void real::sprintf(char *str, int ndigits) const
     1318{
    13081319    real x = *this;
    13091320
    13101321    if (x.m_signexp >> 31)
    13111322    {
    1312         printf("-");
     1323        *str++ = '-';
    13131324        x = -x;
    13141325    }
     
    13161327    if (!x)
    13171328    {
    1318         printf("0.0\n");
     1329        std::strcpy(str, "0.0\n");
    13191330        return;
    13201331    }
     
    13351346    {
    13361347        int digit = (int)floor(x);
    1337         printf("%i", digit);
     1348        *str++ = '0' + digit;
    13381349        if (i == 0)
    1339             printf(".");
     1350            *str++ = '.';
    13401351        x -= real(digit);
    13411352        x *= R_10;
     
    13431354
    13441355    /* Print exponent information */
    1345     if (exponent < 0)
    1346         printf("e-%i", -exponent);
    1347     else if (exponent > 0)
    1348         printf("e+%i", exponent);
    1349 
    1350     printf("\n");
     1356    if (exponent)
     1357        str += std::sprintf(str, "e%c%i", exponent > 0 ? '+' : '-', -exponent);
     1358
     1359    *str++ = '\0';
    13511360}
    13521361
Note: See TracChangeset for help on using the changeset viewer.