0

I'm having some trouble converting a value from double to int. After my conversion of the number with value of 1 and 2 in the tenth position, the value being converted is actually deducted by one. Can someone help me fix this problem?

#include <iostream>
#include <cstring>
#include <cmath>

typedef char* BookName;

using namespace std;

class DecimalBookInfo
{
    public:
        DecimalBookInfo(char inName[], double number);

    private:
        BookName name;
        double code;
        bool verifyCode(double number);

};

int main()
{
    char name[] = "TestBook";
    DecimalBookInfo testBook(name, 230.1);
}

DecimalBookInfo::DecimalBookInfo(char inName[], double number)
{
    // initiate new cstring
    name = new char[strlen(inName)];
    strcpy(name, inName);
    
    if (verifyCode(number))
        code = number;
    else
    {
        cout << "Wrong code...\n";
        exit(1);
    }
}

bool DecimalBookInfo::verifyCode(double number)
{
    double areaCode = floor(number);
    cout << areaCode << endl;
    double subCode = ((number - areaCode) * 100.0);

    cout << static_cast<int>(subCode) << endl;

    if (areaCode > 999 || areaCode < 100 || 
    ((subCode - 10) != 0))
    {
        return false;
    }

    return true;
}

The result is:

230 9 Wrong code...

so I'm not sure why this is so. The number after 230 is supposed to be 10. Thank you

swittuth
  • 77
  • 2
  • 5
  • You probably are assuming that `230.1 - 230.0` should equal `.1` exactly. Unfortunately, you can't exactly express "1 tenth" as a floating point, so `0.099999999999994316` is about as close as it gets. – selbie Nov 28 '20 at 06:04
  • duplicate of: https://stackoverflow.com/questions/588004/is-floating-point-math-broken – selbie Nov 28 '20 at 06:04
  • Apart from the concern that you are using floating point (addressed in the duplicate I indicated on closing the question) the call of `strcpy(name, inName)` in the constructor has undefined behaviour, since the preceding `name = new char[strlen(inName)]` does not allocate enough storage to hold the trailing nul character. To hold a string of length `strlen(inName)`, `name` needs to be allocated (at least) `strlen(inName) + 1` characters. – Peter Nov 28 '20 at 06:04

0 Answers0