十进制二进制用C [英] Decimal to Binary in C
问题描述
我要创建一个程序,加减2个数字。然后,我要输出这个答案分成不同的基地。
I'm creating a program that adds and subtracts 2 numbers. Then I have to output this answer into different bases.
我的回答是十进制格式,为long double类型,如:
My answer is in decimal format, of type long double, such as:
long double answer;
answer = numberOne + numberTwo;
我想这个答案转换成二进制。现在,我刚才在我的计划,这是否使用code,但有一个字符指针:
I want to convert this answer into binary. Now I have code used earlier in my program that does this, but with a char pointer:
char * decimalBinary (char * decimalNumber)
{
bool zeroFront = true;
int i;
int z;
int j = 0;
int n = atoi(decimalNumber);
char * binaryNum = malloc(32+1);
binaryNum[32] = '\0';
int current_index=1;
int end_index = strlen(decimalNumber)-1;
//Error check for valid decimal input, needed error check for beginning of code
while(current_index <= end_index)
{
if(decimalNumber[current_index] != '0' &&decimalNumber[current_index] != '1' &&decimalNumber[current_index] != '2' &&decimalNumber[current_index] != '3' &&decimalNumber[current_index] != '4' &&decimalNumber[current_index] != '5' &&dec[current_index] != '6' &&dec[current_index] != '7' &&decimalNumber[current_index] != '8' &&decimalNumber[current_index] != '9')
{
binaryNum[0] = -8;
return binaryNum;
}
current_index++;
}
for (i = 31; i >= 0; i--) {
z = n >> i;
if (z & 1)
{
binaryNum[j] = '1';
j++;
zeroFront = false;
}
else if (!zeroFront)
{
binaryNum[j] = '0';
j++;
}
}
binaryNum[j] = '\0';
return binaryNum;
}
我的preferred解决方案是使用code我已经在我的计划,我的回答转换成二进制格式,但你可以看到参数是相互矛盾的,我不知道如何去这样做。
My preferred solution is to use the code I already have in my program to convert my answer into a binary format, but as you can see the parameters are conflicting, and I'm not sure how to go about doing that.
这是从我的程序具有可重用code减损另一种可能的解决方案是创建一个不同的功能一起,一个十进制数转换为二进制,但接受long类型double的参数,这是一个有点不清楚我也是。
Another possible solution that detracts from having reusable code in my program, is to create a different function all together that converts a decimal to a binary, but accepting a parameter of type long double, which is a bit unclear to me as well.
编辑:
取而代之的长双
,我的答案是类型 INT
。
Instead of long double
, my answer is of type int
.
推荐答案
如果你真的想重用你的功能,无需修改,您可以将答案
成十进制字符串和该字符串传递给你的函数。
If you really want to reuse your function without modifications, you can transform answer
into a decimal string and pass the string to your function.
char stringAnswer[20];
sprintf(stringAnswer, "%d", answer);
printf("the binary answer is %s\n", decimalBinary(stringAnswer));
但是,一个更好的解决方案应该是功能 decimalBinary
分裂成两个功能:第一个检查所有的数字都OK,而第二个转换一个 INT
成二进制字符串。
然后,你就可以直接调用与答案
第二个函数的参数。
But a better solution should be to split the function decimalBinary
into two functions : the first one to check that all digits are ok, and the second one to convert a int
into a binary string.
Then you'll be able to call directly this second function with answer
as parameter.
这篇关于十进制二进制用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!