2014-01-25 114 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'。 –