-1

I'm doing homework and I have no idea why the %lf selector isn't working. I have to take a line of characters and determine if they can be a floating point or whole number and then print that number. Here's the code:

#include <stdio.h>

int main() {
    char ch;
    int isNumber = 1, dot = 0, negativeMult = 10;
    double result = 0;

    printf("\nEnter characters: ");
    scanf("%c", &ch);
    while (ch != 10) {
        if ((ch >= '0' && ch <= '9')) {
            if (dot) {
                result = result + (ch - '0') / negativeMult;
                negativeMult *= 10;
            } else {
                result = result * 10 + (ch - '0');
            }
        } else
        if (ch == '.')
            if (dot)
                isNumber = 0;
            else
                dot = 1;
        else {
            isNumber = 0;
            break;
        }
        scanf("%c", &ch);
    }

    if (isNumber)
        printf("\nThe number is %lf", result);
    else
        printf("\nEntered characters are not able to be a number.");

    return 0;
}

Edit: I forgot output. Sorry. Input: Enter characters: 123.648

Output: The number is 123.000000

chqrlie
  • 131,814
  • 10
  • 121
  • 189
ProGamer2711
  • 451
  • 1
  • 5
  • 18

1 Answers1

0

the error is here:

result = result + (ch - '0') / negativeMult;

(ch - '0') / negativeMult is integer division and it is always 0

it has to be

result = result + (double)(ch - '0') / negativeMult;
  • some more small errors amendments:
int main(void)
{
      char ch;
        int isNumber = 1, dot = 0, negativeMult = 10;
        double result = 0;
        int scanfresult;

        printf("\nEnter characters: ");
        scanfresult = scanf("%c", &ch);
        while (ch != '\n' && scanfresult == 1)
        {
                if ((ch >= '0' && ch <= '9'))
                {
                        if (dot)
                        {
                                result = result + (double)(ch - '0') / negativeMult;
                                negativeMult *= 10;
                        }
                        else
                        {
                                result = result * 10 + (ch - '0');
                        }
                }
                else if (ch == '.')
                        if (dot)
                                isNumber = 0;
                        else
                                dot = 1;
                else
                {
                        isNumber = 0;
                        break;
                }
                scanfresult = scanf("%c", &ch);
        }

        if (isNumber)
                printf("\nThe number is %f", result);
        else
                printf("\nEntered characters are not able to be a number.");

        return 0;
}

https://godbolt.org/z/nTKdjYsz8

0___________
  • 60,014
  • 4
  • 34
  • 74