C语言转换数基

标签 c radix base-conversion

我需要一个程序:可以转换特定基数中的任何数字并将其转换为另一个基数。它必须适用于实数(例如 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,然后将这两部分分别转换为你喜欢的基数,然后将它们相加。

See this

希望这有帮助

关于C语言转换数基,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53458531/

相关文章:

c - 通过显式算术计算元素指针是否有效?

performance - 基数排序的最佳基础

字符数组未使用 %s 打印

从其字节计算整数会给出奇怪的错误结果

c - 如果在运行时之前不知道它们的数量,如何使用 POSIX C 线程?

c - 段错误(核心转储): scanf int data to array with C

c - 从内存中获取操作数的最坏情况时间

Django 错误迁移嵌套模型而不迁移基础模型

php - 基本 href 不适用于 IE - 替代方案?

java - 使用 Java 的 Integer.toString() 以 26 为基数作为字母