Write a C function that returns nothing, but does something like this: Enter a number: >>> 23879 the number 23879 has 5 digits. Enter a number: >>> 3.14159265359 The number 3.14159265359 has 12 digits
challenging huh.
alright just do the first part, which only accepts integers
i dont know how to write the code exactly, but you can do that by, take the log base 10 of that number, round down, then add one to count the digit.
log base 10? O.o what about the modulo operator
Hmm let c be the number c%10 = b c - b = c/10 c%10 = b c- b = c/10 hmm run this process in a loop and we will check if c <= 10 at the end of the loop i + 1 must be the count
the log base 10 trick works!
but it only works for non-negative numbers... how do I fix that?
make the number positive if it's negative
hah alright those all work
now how do I count real numbers like 3.14159265359
is there some function which separates out the int and frac part?
you can always make one in C :-D
Oh Cool, so how do you do that?
void ndigits(void) { enum {NUMLENGTH = 100}; char number[NUMLENGTH]; char c; int i, digits; digits = i = 0; printf("Enter a number: "); while ((c = getchar()) != '\n') { number[i++] = c; if (c != '-' && c != '.') ++digits; } number[i] = '\0'; printf("The number %s has %d digits", number, digits); }
too bad if i enter something like 'HELLO' it thinks that's a 5 digit number.
void ndigits(void) { typedef enum {false, true} bool; enum {NUMLENGTH = 100}; char number[NUMLENGTH]; char c; bool is_a_number; int i, digits; digits = i = 0; is_a_number = true; printf("Enter a real number (base 10): "); while ((c = getchar()) != '\n') { number[i++] = c; if (c != '-' && c != '.' && is_a_number) { (c - '0' < 0 || c - '0' > 9) ? is_a_number = false : ++digits; } } number[i] = '\0'; if (! is_a_number) { printf("%s is not a number.\n", number); } else { printf("The number %s has %d digits", number, digits); } }
how do I suppress the "comparison between unsigned and signed" warning?
There now it's refactored: int ndigits(void) { typedef enum {false, true} bool; enum {NUMLENGTH = 100}; char* number = malloc(sizeof(number) * NUMLENGTH); unsigned char c; bool is_a_number; int i, digits; digits = i = 0; is_a_number = true; printf("Enter a real number (base 10): "); while ((c = getchar()) != '\n') { number[i++] = c; if (c != '-' && c != '.' && is_a_number) { if (c - '0' < 0 || c - '0' > 9) { is_a_number = false; } else { ++digits; } } } number[i] = '\0'; if (! is_a_number) { printf("%s is not a base 10 number.\n", number); } else { printf("The number %s has %d digits", number, digits); } free(number); return is_a_number; }
How do I refactor it further?
Also, can anyone implement it in Python?
go to computer science section?
Nobody's there :-P but I'll try
Join our real-time social learning platform and learn together with your friends!