문제

I was given an assignment to create a procedure that scans a float, called getfloat.

for some reason, I am getting random values. If I enter "1" it prints 49.Why does this happen? And also, when i input values, I can't see them on the screen? when I use scanf for example i see what i hit, on the little black screen. but now the screen is just blank, and when i click enter it shows a bad output:

Example - input: -1. Output: 499.00000 Here is my code:

#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;
}
도움이 되었습니까?

해결책

There are a number of issues.

1) Your posted code does not match your example "input: -1. Output: 499.00000", I get 0 due the lack of a getch() after finding a '-'. See #6.

1) 'c' is a character. When you enter '1', c took on a code for the letter 1, which in your case being ASCII coding, is 49. To convert a digit from its ASCII value to a number value, subtract 48 (the ASCII code for the letter '0', often done as c - '0'

*num=(*num*10)+c;
*num+=c/exponent;

becomes

*num = (*num*10) + (c-'0');
*num += (c-'0')/exponent;

2) Although you declare c as a float, recommend you declare it as an int. int is the return type from getch().

3) Function getch() is "used to get a character from console but does not echo to the screen". That is why you do not see them. Consider getchar() instead.

4) [Edit: delete Avoid =-. Thank-you @Daniel Fischer]

5) Your exponential calculation needs rework. Note: your exponent could receive a sign character.

6) When you test if(c=='-'), you do not then fetch another c. You also might want to test for else if(c=='+') and consume that c.

Good luck in your C journey.

다른 팁

49 is the Ascii code for the number 1. So when (0'<=c && c <='9') you need to subtract '0' to get the number itself.

A small hint: 49 is the ASCII for the character 1. You are using getch(), which gives you the return value char.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top