我创建了这个函数来转换一个数字'd'在基地10到数字x在基地'b',不幸的是,该函数不打印,有人能帮助我吗?
// I don't understand why it doesn't print me the encode
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 20
// the function created to convert a number 'd' in base 10 to a number in base 'b'
char *encode(unsigned int d, unsigned char b){
if(b<2||b>16) return NULL;
char * resto = calloc (SIZE, sizeof(char));
int i=1;
while(d>0){//rimanenza d%b
char rimanenza = d%b ;
d = d/b;
if (b>10 && b<=16){//if the base is between 10 and 16 'rimanenza' can't be a number
if (rimanenza == 10) rimanenza = 'A';
if (rimanenza == 11) rimanenza = 'B';
if (rimanenza == 12) rimanenza = 'C';
if (rimanenza == 13) rimanenza = 'D';
if (rimanenza == 14) rimanenza = 'E';
if (rimanenza == 15) rimanenza = 'F';
}// save into resto from the end
resto [SIZE - i] = rimanenza;
i++;
}
return resto ;
}
int main (){
unsigned int d = 126;
unsigned char b = 3;
char *encoded = encode (d,b);
printf ("%u in base %u = %s\n",d,b,encoded);
free(encoded);
}
1条答案
按热度按时间blmhpbnm1#
至少这些问题:
rimanenza < 10
时,数字未转换为正确字符**当
rimanenza
在[0'...'9]范围内时,将其转换为字符['0 '...' 9']。d
最初为0时,while(d>0){
无法形成"0"
。**return resto ;
无法返回resto[]
填充部分的开头。更像是:
calloc()
失败,则无法测试**#define SIZE 20
不足以满足encode(UINT_MAX, 2)
的要求。@M欧姆代码需要在所有字符后加上
'\0'
,才能成为 * string *。考虑只分配所需的资源。
未经测试的维修