0

Basically i tried to output a double variable with but only PrintDigit(char ). Here is my code

void    printDigit(const char c)
{
cout << c ;
}

void    PrintDigits(double target)
{
    if (target < 0)
    {
        printDigit('-');
        target = -target ;
        PrintDigits((int)target / 10);
    }
    else if ((int)target / 10 == 0)
    {
        printDigit('0' + (int)target % 10);
        if (target - (int)target % 10 != 0)
        {
            target -= (int)target % 10;

        do {
            target *= 10 ;
            //for debugging
            cout << endl << target << endl;
            cout << floor(target)<<" "<<ceil(target)<<endl;
        } while (floor(target) != ceil(target));

        printDigit('.');
        PrintDigits(target);
    }
}

}

And there are some strange problems ,here is the output when i tried to input 3.53: check the output when target==53!

My question is why floor(target)==52 while target==53 ? And is there any better way to do this ?(with only PrintDigit(char) function and don't transfer the double variable to string)

yadance nick
  • 101
  • 1
  • 5
  • Why are you calling `PrintDigits()` from within `PrintDigits()`? – ifconfig Aug 16 '17 at 01:06
  • what is floor(target)<<" "< – Hariom Singh Aug 16 '17 at 01:09
  • The reason you're wondering why `floor(53)` is `52` is because, as the linked question explains, floating point math is broken. See the linked question for a detailed explanation. – Sam Varshavchik Aug 16 '17 at 01:11
  • @SamVarshavchik Thx for ur answer.I thought that was the problem. BTW du u have any suggestions to correct my program ? – yadance nick Aug 17 '17 at 02:34
  • @ifconfig for recursion – yadance nick Aug 17 '17 at 02:35
  • @HariomSingh this is the complete code.I just output the value of floor(target) and ceil(target) for debugging – yadance nick Aug 17 '17 at 02:36
  • The best suggestion for you is to go [and make an appointment with your rubber duck](https://en.wikipedia.org/wiki/Rubber_duck_debugging). For example, it makes no sense whatsoever to divide the number by 10 if it's negative, without doing anything else. That does not compute. The logic of the shown code is fundamentally broken. This cannot be fixed, and must be rewritten from scratch, after the revised algorithm gets your rubber duck's stamp of approval. – Sam Varshavchik Aug 17 '17 at 10:49
  • @SamVarshavchik Yep , i checked my code again i did find some logic problem .I made minor alterations to make the code more clear and it worked.Thx so much dude! – yadance nick Aug 19 '17 at 07:23

0 Answers0