2015-06-05 50 views
-1

所以,我創建了一個計算三角形面積的程序,我需要它告訴用戶他是否鍵入了一個字母或負數,以便我創建的代碼: 我需要使用ISDIGIT如何使此代碼工作(isdigit)

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

int main() { 
    float a, b, c; 
    float s=0, ar1=0, ar2=0; 
    printf("Inform the value of side A."); 
    fflush(stdin); 
    scanf("%f",&a); 
    while(a<=0||isdigit((int)a)){ 
     printf("Invalid value."); 
     fflush(stdin); 
     scanf("%f",&a); 
    }printf("Inform the value of side B."); 
    fflush(stdin); 
    scanf("%f",&b); 
    while(b<=0||isdigit((int)a)){ 
     printf("Invalid value."); 
     fflush(stdin); 
     scanf("%f",&b); 
    }printf("Inform the value of side C."); 
    fflush(stdin); 
    scanf("%f",&c); 
    while(c<=0||isdigit((int)a)){ 
     printf("Invalid value."); 
     fflush(stdin); 
     scanf("%f",&c);} 
     s=((a+b+c)/2); 
     ar1=(s*(s-a)*(s-b)*(s-c)); 
     ar2=pow(ar1,0.5); 
    printf("The semiperimeter is %f",s); 
    printf("The area of the triangle is%f",ar2); 
    system ("pause"); 
    return 1; 
} 

但是,當我編譯/運行,輸入「X」,或當我本來是要鍵入數字「布拉布拉」,沒有任何反應,和程序不警告我,我該怎麼辦?

+0

另外,我是一個初學者,所以我不知道有多少功能,用C –

+0

刪除所有這些'fflush(標準輸入)'。在很多實現中都是UB。 –

+0

什麼是UB?我刪除它,什麼也沒有發生 –

回答

1

首先,根據C11標準,在stdin上使用fflush是未定義的行爲,儘管它在某些實現中已被很好地定義。其次,你不能簡單的使用isdigit這樣的方式。一旦%f看到字符等無效數據,scanf終止並且相應的參數不變。另外,在未初始化的變量上使用isdigit會導致未定義的行爲。

你可以做的是檢查返回值scanf。如果成功,代碼中的所有三個scanf都會返回1。


固定碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 
#include <ctype.h> //Unused header 


void flushstdin() //Removes all characters from stdin 
{ 
    int c; 
    while((c = getchar()) != '\n' && c != EOF); //Scan and discard everything until a newline character or EOF 
} 

int main() { 

    float a, b, c; 
    float s=0, ar1=0, ar2=0; 

    printf("Inform the value of side A\n"); 
    //fflush(stdin); Avoid this to make your code portable 
    while(scanf("%f",&a) != 1 || a <= 0){ 
     printf("Invalid value\n"); 
     flushstdin(); //Alternative way to flush stdin 
    } 

    printf("Inform the value of side B\n"); 
    //fflush(stdin); 
    while(scanf("%f",&b) != 1 || b <= 0){ 
     printf("Invalid value\n"); 
     flushstdin(); //Alternative way to flush stdin 
    } 

    printf("Inform the value of side C\n"); 
    //fflush(stdin); 
    while(scanf("%f",&c) != 1 || c <= 0){ 
     printf("Invalid value\n"); 
     flushstdin(); //Alternative way to flush stdin 
    } 

    s=((a+b+c)/2); 
    ar1=(s*(s-a)*(s-b)*(s-c)); 
    ar2=pow(ar1,0.5); 

    printf("The semiperimeter is %f\n", s); 
    printf("The area of the triangle is %f\n", ar2); 
    system ("pause"); 
    return 0; // 0 is usually returned for successful termination 
} 

另外,最好是在printf串的端部如在上述方案看出添加換行符。他們

  • 提高可讀性
  • 刷新標準輸出
+0

謝謝,既然如此,那麼多! –

+0

嗯,但現在,當我計算面積時,它總是說:「三角形的面積是-1。#IND00這是什麼意思?@Cool Guy –

+0

不知道。你的輸入是什麼? –