2014-01-25 38 views
-2

我需要一點幫助。代碼看起來很好。但是當我運行並輸入一個非數字的數字時,它會無限地顯示消息框錯誤,並且不會停止,除非我終止程序。有人可以告訴我一種解決方法嗎?謝謝!無限消息框

CODE:

#include <stdio.h> 
    #include <stdlib.h> 
    #include <windows.h> 
    #include <ctype.h> 
    #define pi 3.1416 

    int main() 
    { 
     float rad, area, dia, circ; 
     int radint; 
     char resp; 
     start: 
     system("cls"); 
     printf("Chapter 1 \t\t\tProblem 1\n\n"); 
     printf("Input the circle's radius: "); 
     radint = scanf("%f", &rad); 
     if(rad < 0) 
     { 
      MessageBox(0, "There cannot be negative measurements.", "Negative Value", 0); 
goto start; 
     } 
     if(radint < 1) 
     { 
      MessageBox(0, "Non-numeric value is inputted.", "Character Value", 0); 
      goto start; 
     } 
     dia = rad * 2; 
     circ = 2 * pi * rad; 
     area = pi * rad * rad; 
     printf("\n\nDiameter = %0.2f | Circumference = %0.2f | Area = %0.2f\n\n", dia, circ, area); 
     printf("Try again? [Y/N]: "); 
     ret: 
     resp = getchar(); 
     switch(resp) 
     { 
      case 'y': goto start; 
      case 'n': return; 
      default: goto ret; 
     } 
    } 
+1

附註:請不要'#define pi 3.1416'。即使Visual Studio應該有'',它定義了'M_PI'。 –

+0

「isalpha()C Function faulty?」 - ** No。** – 2014-01-25 10:42:14

+0

找到一種不使用'goto','system(cls)'和特定於操作系統的東西(比如'MessageBox')來製作這個程序的方法,你的程序可能會變好10-100倍。在練習過程中,您可能也可以解決您的問題。 – Brandin

回答

3

您在float調用isalphaisalpha需要一個小整數。

從標準:

頭聲明有用若干功能進行分類 和映射characters.198)在所有情況下的參數爲int,它的 值應是可表示爲無符號char或 等於宏EOF的值。如果參數有任何其他值,則 的行爲是不確定的。

有做作的方式,使在floatisalpha工作,但它可能不是你想要的。

根本不需要使用isalpha。正如Stefano Sanfilippo在另一個答案中所建議的,您只需檢查scanf返回的值:成功匹配的數量

換句話說,如果你要求一個浮點數並且scanf返回1,那麼通過所有的方法用戶必須鍵入一些必須看起來像float的東西,你可以使用它。

+0

我剛剛那樣做了,它是固定的。但是仍然有一個問題:如果我輸入一個錯誤值(任何不是數字的),對話框不會停止顯示。它無限循環。 – Wix

0

isalpha期望一個int作爲輸入(實際上解釋爲unsigned charEOF),而不是一個浮點數。您作爲參數傳遞的號碼被傳送到int,並且它落在字母數字範圍之外。

可以檢查數量是否正確通過測試的scanf返回值分析:

int converted = scanf("%f", &rad); 

if (converted < 1) { 
    MessageBox(0, "Non-numeric value is inputted.", "Character Value", 0); 
} 

和去除isalpha分支。

+0

請定義「它不會工作」。輸出值是否錯誤?或者是什麼? –

+0

如果我輸入一個數值,它現在可以工作。但是如果我輸入一個非數字值,對話框的外觀無限循環。 – Wix

+0

我想你應該重做'goto'。嘗試在上面的if中的MessageBox之後添加'goto start;'。更好的是,擺脫那些'goto'。 –