Search code examples
ccodeblocksscientific-notation

How can I turn off Exponenntial Notation in C?


please enter num1 , op , num2
2e2+6
result= 206.000000

Process returned 0 (0x0)   execution time : 8.657 s
Press any key to continue.

(How to use) ... any way to turn off this !


Solution

  • You cannot do this directly, there is no standard format specifier for the scanf function family that rejects scientific notation (such as 1e3) for floator double and there is no directy way to "turn off" the scanfs accepting of numbers in scientific notation.

    What you can do is read the input as string. Then you check if the string contains 'E' or 'e' and reject if that's the case.

    This naive approach should give you an idea what you could do:

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
      float x = 0;
    
      do
      {
        char buffer[100];
        scanf("%s", buffer);
    
        if (strchr(buffer, 'E') != NULL || strchr(buffer, 'e') != NULL)
        {
          printf("Rejected\n");
        }
        else
        {
          sscanf(buffer, "%f", &x);
          break;
        }
      } while (1);
      //...
    }
    

    Instead of checking explicitely for the presence of E and e, you could also check for the presence of any non digit and non decimal point character, IOW reject if the buffer contains any of characters not included in [0123456789.]

    Of course you should eventually put this functionality into a function.