-1

I've been writing a code of the Fibonacci sequence (iteratively). It scans a number n, and it outputs F(n) until I input -1. The problem is that first, I need to check if the number is not an integer. If it is not an integer, it should output "error".

#include<stdio.h>
#include<ctype.h>

int main(){
    float n=0;
    int x=0,ver=0,Fn=0,last1=0,last2=0;

    scanf("%f",&n);
    ver=n;
    while(n!=-1){
        if(n-ver!=0 || !isdigit(ver)){
            printf("Error\n");
        }
        else if(n==1 || n==2){
            printf("1\n");
        } else{
            last1=1;
            last2=1;
            for(x=3;x<=n;x++){
                Fn=last1+last2;
                last1=last2;
                last2=Fn;
            }
            printf("%d\n",Fn);
        }
        getchar();
        scanf("%f",&n);
        ver=n;
    }
return 0;
}

I've tried with isdigit and !isdigit and I still get wrong outputs. It should output error when I input things like .11$, 1.- , 1.23,KDhf, etc.

Angela M.
  • 51
  • 8
  • Why not *read* an integer? Then `scanf` will fail if you give something that's not. – Some programmer dude Nov 06 '16 at 07:15
  • @Someprogrammerdude what do you mean? sorry, my English is not good – Angela M. Nov 06 '16 at 07:16
  • Check return value of `scanf`. – BLUEPIXY Nov 06 '16 at 07:16
  • You want something like this? `ver < '0' || '9' < ver` instead of `!isdigit(ver)` (character codes for decimal digits is consecutive, according to the C standard) -- sorry, this should be "No". How confusing the existence of `isdigit()` here is! – MikeCAT Nov 06 '16 at 07:23
  • Read the documentation of `scanf`. Don't re-invent the wheel! – too honest for this site Nov 06 '16 at 07:24
  • Why not with `isdigit()`? What's the reason for that constraint? – user207421 Nov 06 '16 at 07:26
  • I would use `fgets()` to read a line of input, and then `strtol()` — carefully — to check that the value entered was all integer plus white space. Often, I'd use `fgets()` and `sscanf()`, but determining whether the input is an integer is a pain with any of the `scanf()` family — see the discussion on [Read only floating point number with fraction and reject integers](http://stackoverflow.com/questions/40323390/); it's not an identical problem, but it is indicative of the problems you can run into. – Jonathan Leffler Nov 06 '16 at 07:31

1 Answers1

0

For finding fibonacci numbers, you don't need n to be of float type. You can use any integer type.

To find if the number was scanned successfully, check the return value of scanf().

int n = 0;
if (scanf("%df",&n) != 1) {
    printf("Error\n");
    exit(EXIT_FAILURE);
}

And remove this part:

    if(n-ver!=0 || !isdigit(ver)){
        printf("Error\n");
    }

isdigit() can only handle single digit numbers.

P.P
  • 117,907
  • 20
  • 175
  • 238