gpt4 book ai didi

c - 如何在C中将整数放入 vector 中?

转载 作者:行者123 更新时间:2023-11-30 16:48:37 24 4
gpt4 key购买 nike

我用 C 语言编写了一个函数,将二进制数转换为十进制数:

while (n != '\n')
{
scanf("%c",&n);
if (n == '1')
var = var * 2 + 1;
else if (n == '0')
var *= 2;
}

现在我想知道如何将小数点后的每个数字放入字符数组中。

例如:var=145是转换后的数字,所以数组应该是这样的:

char array[n_bit]={1,4,5};

最佳答案

这应该可以满足您的需要(至少按照我的理解):

// returns the number of decimal digits in 'num'
unsigned int getNumDigits(unsigned int num)
{
unsigned int res = 1; // when the 'num' is 0, the number of digits is 1
num /= 10;

while (num)
{
res++;
num /= 10;
}

return res;
}

// fill the 'array' with chars which represent the digits in the given 'inputNum'
// so that if inputNum=135, array[0]='1', array[1]='3' and array[2]='5'
// assuming 'array' contains nothing but '\0's when given as input
int fillDecimalVector(unsigned int inputNum, char array[], size_t arr_size)
{
unsigned int fillIdx = 0;
unsigned int numOfDigits = getNumOfDigits(inputNum);

if (numOfDigits > arrSize)
return -1;

// when the 'inputNum' initial value is 0 we are expected to fill '0'
while (inputNum || !fillIdx)
{
array[numOfDigits - fillIdx - 1] = '0' + (char)(inputNum % 10);
fillIdx++;
inputNum /= 10;
}

return 0;
}

注意

我没有尝试编译它,因此可能存在轻微的语法错误。

关于c - 如何在C中将整数放入 vector 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42885804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com