getchar double number

Guys I've written something but ı still lacking

QUESTİON :Write a program that only uses getchar() for input, and can input a double number. You can use printf() to print the integer and confirm it was read in correctly. Assume the number is positive.

Solution ways : 1-) You should include the ‘.’ character before the rational part.
2-) Rationalizing the input character data needs extra arithmetic process, that is, reciprocalization !
Important: You should merge your reciprocaling operator process in looping just after the getchar() of ‘.’


my code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
int main() {
    int i = 0;
    char num;

    printf("enter the number : ");

    while ((num = getchar()) != '\n') {
        if (num > '9' || num < '0')
            continue; 
       {
		 i *= 10;
        i += num - '0'; }
    }

    printf("entered number: %d\n", i);
    return 0;
}



code doesn't make dot-like conversions

The answer can be like this:
https://i.hizliresim.com/nQoRAN.png
Last edited on
up
to read in a double you should probably accept chars like -{., depend on locale},e and maybe a few others. you only accept 0-9.

if I type 3.14, what does your program do? How do you fix that?

one way is just to dump the thing into a string, so long as the chars are valid, and then use atof to convert it to a double.
if you can't use atof and have to re-create it, you have to divide by powers of 10 after the decimal.
Last edited on
Once you read the decimal point, exit the loop that enters the integer part and enter a loop that reads the fractional part.

Do you need to handle exponents of 10, like 4.56E10?
Topic archived. No new replies allowed.