+ 2

How can I convert a long long into an array in C?

Hello everyone, I'm working on a project that does an algorithm with the given input. I have the input stored in a long. with the given input, I need to convert “number” into an array so I can have access to each digit. for example, if “number = 73757383” I need to convert that into an array: array = [7, 3, 7, 5, 7...] to be able to do the algorithm (multiply every other digit, then add the others together). But I can’t seem to figure out how to do this. Any help is appropriate. Also just as a note, I'm including the cs50 library. Thank you! my code is also in this solo link. https://code.sololearn.com/ca1442A6A25a #include <stdio.h> #include <cs50.h> #include <math.h> int main(void) { long credit; int number; do { credit = get_long("Number: "); number = floor(log10(credit) + 1); printf("%lu\n", credit); } while (number < 13 || number > 16); }

12th Mar 2021, 6:47 PM
David
David - avatar
5 odpowiedzi
+ 2
You already figured out how many digits you have (-> floor(log10(x)+1)). Now you only need to a) create an array with the size you need (-> malloc) b) populate the array with the digits Hint: you get the last digit with %10 and you can cut the last digit when dividing by 10 Hope this helps.
13th Mar 2021, 8:52 PM
Alex
Alex - avatar
+ 3
David You got any example of input and desired output (result)? I don't think I understand your Description, "touch each digit" and all didn't come too clear unfortunately ...
13th Mar 2021, 3:15 AM
Ipang
+ 1
"cs50" seems to be not available, I'm having that "compilation terminated" while trying to run the code. And yes, you probably have to store every digit separately in the array floor function just rounds down value inside these round braces. log10 gives you result of logarithm with base 10 of "credit",
12th Mar 2021, 7:51 PM
Michal Doruch
0
Michał Doruch thank you for your help. really Appreciate it.
12th Mar 2021, 8:58 PM
David
David - avatar
0
Ipang sorry i didnt explain it clear. i need to convert “number” into an array so i can have access to each digit. for example, if “number = 73757383” i need to convert that into an array like array = [7, 3, 7, 5, 7...]
13th Mar 2021, 1:07 PM
David
David - avatar