“copy” elements of array in order into an “int”? C [closed]

别来无恙 提交于 2019-12-27 06:11:08

问题


It may be a really simple question, but I need to copy two int values that are in array[0] and array[1] into a single integer.

As instance if array[0]=1 and array[1]=6, I need the integer to be equal to "16". Any element of the array has a range from 0 to 9.

What chances do I have? Thank you a lot!


回答1:


Does array[0] always represent the 10's place and array[1] always represent the 1's place? Will array[0] or array[1] ever have a value greater than 9 or less than 0? Will there ever be an array[2] or an array[3] to represent a 3 digit or a 4 digit number?

If the answer to the above questions are Yes, No, and No, then isn't the answer simple arithmetic?

int result = (array[0] * 10) + array[1];

If the data isn't pre range-checked, then you'll need to add that step. Even if the data IS pre range-checked, you should consider adding that step anyway to make extra sure.

'10' is also a magic number in the above example. It would probably be wise to not hard-code 10, but base it off of the size of the array. Consider the case where there IS an array[2] . . . array[n]. What then?




回答2:


An easy way to do it, is to convert your integers to strings, contact than, and then convert again, this time from string to int.

char s1[30]; // String that will hold the first integer
char s2[15]; // String that will hold the second integer

int intResult;

First convert int to string:

sprintf(s1, "%d", array[0]);
sprintf(s2, "%d", array[1]);

Than join the 2 strings together:

s1 = strcat(s1,s2);

Then convert the string result to integer. intResult = atoi(s1);



来源:https://stackoverflow.com/questions/13445222/copy-elements-of-array-in-order-into-an-int-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!