我试图提示用户输入数字,然后对其进行扫描以查看它是否为浮点数。即使输入不带小数的数字,它也会回来表示它是浮点数。如果输入为浮点型,则该函数应返回1,否则为0。我感觉到我的函数逻辑存在问题。任何帮助,将不胜感激。谢谢!
#include <stdio.h> //including for the use of printf
#pragma warning(disable: 4996) // turn off warning about sscanf()
/* == FUNCTION PROTOTYPES == */
double getDouble(double *pNumber);
double *pNumber = NULL;
int main(void)
{
double returnedValue = 0;
double userInput = 0;
int runOnce = 0;
printf("Please Enter a float:");
userInput = getDouble(&returnedValue);
while (runOnce == 0)
{
if (userInput == 1)
{
printf("Your number is a valid float!\n");
printf("%lf", returnedValue);
}
else
{
printf("Your number is not a float!\n");
}
printf("Press ENTER key to Continue\n");
getchar();
}
}
#pragma warning(disable: 4996)
double getDouble(double *pNumber)
{
char record[121] = { 0 }; /* record stores the string from the user*/
double number = 0;
/* fgets() - a function that can be called in order to read user input from the keyboard */
fgets(record, 121, stdin);
if (scanf("%lf", &number) == 1)
{
*pNumber = number;
return 1;
}
else
{
return 0;
}
}
答案 0 :(得分:1)
您同时呼叫fgets()
和 scanf()
。使用一个或另一个,但不能同时使用。如果要使用fgets()
,请使用sscanf()
解析其结果。