我只需要弄清楚如何给出错误是用户输入任何不是数字的东西。我已经设置了无法通过或不能通过的代码的值。如何仅接受C中的数字并阻止用户输入字母和特殊字符?
我只需要只接受数字:如果输入一个字母或任何类型的特殊字符我想程序只是取消自己。我怎样才能做到这一点?
#include <stdio.h>
#include <math.h>
int main(void) {
float base, height;
float area;
printf("Please enter the value of base of the triangle: \n");
scanf ("%f", &base);
if(base<.5)
printf("Invalid Input\n");
while (base<.5)
return 0;
if(base>100)
printf("Invalid Input\n");
while(base>100)
return 0;
printf("Please enter the value of height of the triangle:\n");
scanf("%f", &height);
if(height<1)
printf("Invalid Input\n");
while(height<1)
return 0;
if(height>75)
printf("Invalid Input\n");
while (height>75)
return 0;
area = base * height/2;
printf("The area of the triangle for base: %f and height: %f is %f \n", base,
height , area);
return 0;
}
由于OP想要“给出错误是(如果)用户输入任何不是数字的”,这里的弱点在这里。这不会完全消耗“123abc”之类的非digt文本,但将“abc”保留在“stdin”中并且不会出现错误。建议'fgets()'然后'sscanf()/ strtof'。 – chux 2014-09-29 19:26:30