-1
我一直在寫斐波那契數列的代碼(迭代)。它掃描一個數字n,並輸出F(n)直到我輸入-1。問題是,首先,我需要檢查數字是不是一個整數。如果它不是一個整數,它應該輸出「錯誤」。如何在不使用isdigit的情況下檢查C中的數字是不是整數?
#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;
}
我試過用isdigit和!isdigit,我仍然得到錯誤的輸出。它應該輸出錯誤,當我輸入像.11 $,1.-,1.23,KDhf等。
爲什麼不讀*一個整數?那麼如果你給一些沒有的東西,'scanf'將會失敗。 –
@Someprogrammerdude你是什麼意思?對不起,我的英文不好 – Marelisse
檢查'scanf'的返回值。 – BLUEPIXY