我正在读初级C课程我收到了一个作业,告诉我写一个程序,它将二进制和十六进制之间的任意数字的任意数字转换为二进制和十六进制之间的另一个基数.我被要求使用单独的函数来转换和从基数10转换.这是为了帮助我们习惯使用数组. (我们已经覆盖了以前在课堂上的参考.)我已经把它改成了,但我很确定这不是我的意图:
#include <iostream> #include <conio.h> #include <cstring> #include <cmath> using std::cout; using std::cin; using std::endl; int to_dec(char value[],int starting_base); char* from_dec(int value,int ending_base); int main() { char value[30]; int starting_base; int ending_base; cout << "This program converts from one base to another,so long as the bases are" << endl << "between 2 and 16." << endl << endl; input_numbers: cout << "Enter the number,then starting base,then ending base:" << endl; cin >> value >> starting_base >> ending_base; if (starting_base < 2 || starting_base > 16 || ending_base < 2 || ending_base > 16) { cout << "Invalid base(s). "; goto input_numbers; } for (int i=0; value[i]; i++) value[i] = toupper(value[i]); cout << "Base " << ending_base << ": " << from_dec(to_dec(value,starting_base),ending_base) << endl << "Press any key to exit."; getch(); return 0; } int to_dec(char value[],int starting_base) { char hex[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; long int return_value = 0; unsigned short int digit = 0; for (short int pos = strlen(value)-1; pos > -1; pos--) { for (int i=0; i<starting_base; i++) { if (hex[i] == value[pos]) { return_value+=i*pow((float)starting_base,digit++); break; } } } return return_value; } char* from_dec(int value,int ending_base) { char hex[16] = {'0','F'}; char *return_value = (char *)malloc(30); unsigned short int digit = (int)ceil(log10((double)(value+1))/log10((double)ending_base)); return_value[digit] = 0; for (; value != 0; value/=ending_base) return_value[--digit] = hex[value%ending_base]; return return_value; }
我很确定这比它想要的更先进.你觉得我应该怎么做?
我基本上正在寻找两种答案:
解决方法
我不认为你需要内循环:
for (int i=0; i<starting_base; i++) {
它的目的是什么?
相反,您应该获取值为[pos]的字符并将其转换为整数.转换取决于base,所以在单独的函数中可能会更好.
您正在定义char hex [16]两次,每次功能一次.最好只在一个地方做.
编辑1:
既然这是“家庭作业”的标签,我不能给你完整的答案.但是,这里是一个如何to_dec()应该工作的例子. (理想情况下,你应该已经构建了!)
输入:
char * value = 3012,int base = 4,
数学:
Number = 3 * 4^3 + 0 * 4^2 + 1 * 4^1 + 2 * 4^0 = 192 + 0 + 4 + 2 = 198
预期工作循环:
x = 0 x = 4x + 3 = 3 x = 4x + 0 = 12 x = 4x + 1 = 49 x = 4x + 2 = 198 return x;
编辑2:
很公平!所以,这里还有一些:-)
这是一个代码草图.未编译或测试.这是我之前提供的例子的直接翻译.
unsigned to_dec( char * inputString,unsigned base ) { unsigned rv = 0; // return value unsigned c; // character converted to integer for( char * p = inputString; *p; ++p ) // p iterates through the string { c = *p - hex[0]; rv = base * rv + c; } return rv; }