我需要一个程序:可以转换特定基数中的任何数字并将其转换为另一个基数。它必须适用于实数(例如 7.34、3.14 等)
输入:number1、base1、base_to_which_it_must_be_converted 输出:转换后的数字:
我设法编写了这样的程序,但它们不适用于实数。
#include <stdio.h>
#include <string.h>
char reVal(int num)
{
if (num >= 0 && num <= 9)
return (char)(num + '0');
else
return (char)(num - 10 + 'A');
}
void strev(char *str)
{
int len = strlen(str);
int i;
for (i = 0; i < len/2; i++)
{
char temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
}
char* fromDeci(char res[], int base, int inputNum)
{
int index = 0;
while (inputNum > 0)
{
res[index++] = reVal(inputNum % base);
inputNum /= base;
}
res[index] = '\0';
strev(res);
return res;
}
int main()
{
int inputNum = 10, base = 3;
char res[100];
printf("Equivalent of %d in base %d is "
" %s\n", inputNum, base, fromDeci(res, base, inputNum));
return 0;
}
#include <stdlib.h>
#include <stdio.h>
int b,c,x,nr,nr2;
char z;
int main()
{
int num,i,l,b,a[50];
l=0;
printf("introduce the number and its base\n");
scanf("%d",&num);
scanf("%d",&b);
int n;
i=0;
n=num;
l=0;
while (n!=0)
{
l++;
n/=10;
}
n=num;
i=l;
while (n!=0)
{
a[i]= n%10;
n/=10;
i--;
}
i=0;
while(i<=l)
{
x=x*b+a[i];
i++;
}
printf("\n%d",x);
return 0;
}
最佳答案
首先,当您获取实数时,您需要更改 num 的类型。 它应该是“float num;”
如果你想将 3.14 从十进制转换为二进制,那么你需要将其分成两部分,一部分是 3,另一部分是 0.14,然后将这两部分分别转换为你喜欢的基数,然后将它们相加。
希望这有帮助
关于C语言转换数基,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53458531/