我正在学习初学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', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', '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;
}
Run Code Online (Sandbox Code Playgroud)
我很确定这比它本来的更先进.你怎么认为我应该这样做?
我基本上是在寻找两种答案:
我认为你不需要内循环:
for (int i=0; i<starting_base; i++) {
Run Code Online (Sandbox Code Playgroud)
它的目的是什么?
相反,您应该获取字符value[ pos ]并将其转换为整数。转换取决于基数,因此最好在单独的函数中进行转换。
您定义了char hex[ 16 ]两次,每个函数一次。最好只在一个地方进行。
编辑1: 由于这是“作业”标记,我无法给你完整的答案。然而,这里有一个 to_dec() 应该如何工作的例子。(理想情况下,您应该构建这个!)
输入:
char * value = 3012,
int base = 4,
Run Code Online (Sandbox Code Playgroud)
数学:
Number = 3 * 4^3 + 0 * 4^2 + 1 * 4^1 + 2 * 4^0 = 192 + 0 + 4 + 2 = 198
Run Code Online (Sandbox Code Playgroud)
循环的预期工作:
x = 0
x = 4x + 3 = 3
x = 4x + 0 = 12
x = 4x + 1 = 49
x = 4x + 2 = 198
return x;
Run Code Online (Sandbox Code Playgroud)
编辑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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10094 次 |
| 最近记录: |