我正在尝试创建一个程序来检查用户输入的数字是否为 float ,但它不起作用。我尝试使用 scanf
进行检查,但这也不起作用。
#include <stdio.h>
int main(void) {
float num1;
printf("enter number: ");
scanf("%lf", &num1);
if (scanf("%lf")) {
printf("Good \n");
}
else {
printf("Bad \n");
}
}
最佳答案
您是否阅读过有关 scanf(3)
的任何文档? ?
你需要像这样检查返回值
double value;
if (scanf("%lf", &value) == 1)
printf("It's float: %f\n", value);
else
printf("It's NOT float ... \n");
有一种方法我更喜欢,因为它可以对后续输入进行更多控制,scanf()
很少真正有用。而是尝试 fgets()
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
char buffer[100];
double value;
char *endptr;
if (fgets(buffer, sizeof(buffer), stdin) == NULL)
return -1; /* Unexpected error */
value = strtod(buffer, &endptr);
if ((*endptr == '\0') || (isspace(*endptr) != 0))
printf("It's float: %f\n", value);
else
printf("It's NOT float ...\n");
}
关于c - 如何检查用户输入是否是 C 中的 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33621681/