简体   繁体   中英

How can I align two integer arrays by index in C?

I know the question may not seem very clear.

Basically I'm trying to code a program that displays elementary arithmetic calculations (via the console of course) in the same way kids would do.

For instance:

5,294
+ 0,706

= etc

So I have both numbers in separate arrays, split up by digit (so an int array like: {5,2,9,4}).

What I'm trying to learn/figure out is how I would align both sets of digits to the right if they didn't have the same number of digits. For example if instead of 0,706 I had just 706? Currently I would have two arrays, one like {5,2,9,4} and another like so: {7,0,6} – I would need the 4 to be over the 6.

Hopefully that makes sense to you all!

Thanks in advance!

I think this code snippet might generate the sort of output you're looking for, it works with ordinary integers so you don't need to mess around with arrays:

char tmpstr[1];
int total = first + second;
int width = snprintf(tmpstr, 1, "%d", total);
printf("  %*d\n", width, first);
printf("+ %*d\n", width, second);
printf("  %.*s\n", width, "-----------");
printf("= %*d\n", width, total);

Simply look for the length of every single array and find the longest length. Then creating new arrays for every array that does not have that length and start filling these arrays first with the numbers of the old short array and then for the rest of the values fill them up with zeros until you reach index 0. I hope I did understand your question correctly to answer your question with my proposal.

That is of course only valid, if there is no decimal point involved. If there is a decimal point involved you would have to find the maximum number of digits to the left and to the right of that and then create new arrays for every old array that do not meet this criteria and do the same thing as above.

Edit: An even easier way to do it, could be simply by reversing the order of every array, then do your calculations, but carrying the numbers to the right (and not left) and in the end reverse the order of the result.

You need information about your decimal point within your array. Else you could just use integers. I would take the exponent to the base of 10 and make it either my first or my last entry. Once you have this you can use it for shifting your formatting accordingly.

´0,706´ would become ´{-3, 7, 0, 6}´ the first number being the exponent. Then you align your comma like this

//0 -1 -2 -3
   ,  
   ,

and then just put in your number

//0 -1 -2 -3
  0, 7  0  6
   ,

Rinse and repeat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM