我被分配创建一个扫描浮点数的过程,称为 getfloat。
出于某种原因,我得到了随机值。如果我输入“1”,它会打印 49。为什么会发生这种情况?而且,当我输入值时,我在屏幕上看不到它们?例如,当我使用 scanf 时,我会在小黑屏上看到我击中的内容。但现在屏幕只是空白,当我点击输入时,它显示一个错误的输出:
示例 - 输入:-1。输出:499.00000 这是我的代码:
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <ctype.h>
void getfloat(float* num);
void main()
{
float num=0;
printf("Enter the float\n");
getfloat(&num);
printf("\nThe number is %lf\n",num);
getch();
}
void getfloat(float* num)
{
float c,sign=1,exponent=10;
c=getch();
if((!isdigit(c))&&(c!='+')&&(c!='-')) //if it doesnt start with a number a + or a -, its not a valid input
{
printf("Not a number\n");
return;
}
if(c=='-') //if it starts with a minus, make sign negative one, later multiply our number by sign
sign=-1;
for(*num=0;isdigit(c);c=getch())
*num=(*num*10)+c; //scan the whole part of the number
if(c!='.') //if after scanning whole part, c isnt a dot, we finished
return;
do //if it is a dot, scan fraction part
{
c=getch();
if(isdigit(c))
{
*num+=c/exponent;
exponent*=10;
}
}while(isdigit(c));
*num*=sign;
}