【发布时间】:2021-01-16 19:22:20
【问题描述】:
我们假设编写一个程序,从 startBase 中获取一个数字 n,并返回 endBase 中的数字。
例如,如果我输入 ./a.out 1 ABCD 16 10 那么程序应该返回
1 has 1 bit(s)
ABCD (base 16) = 43981 (base 10)
下面是我的转换函数
string converter(string num, int base1, int base2){
int decimal = 0;
string result = "";
if(num == "0"){
return 0;
}
for(int i = num.length() - 1; i >=0; i--){
char current = num[i];
int e;
if(current == 'A'||current == 'B'||current == 'C'||current == 'D'||current =='E'||current == 'F'){
e = (int)current - 55;
}else{
e = (int)current - (int)'0';
}
decimal = decimal + e*pow(e,base1);
}
string strdecimal = to_string(decimal);
while(decimal > 0){
result = to_string(decimal%base2) + result;
decimal = decimal/base2;
}
return result;
}
这就是我在主函数中执行它的方式
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
void outputBinary(unsigned int x);
int countBits(unsigned int n);
string converter(string num, int base1, int base2);
int main(int argc, char **argv){
int a = stoi(argv[1]);
int b = countBits(a);
string c = converter(argv[2], argv[3], argv[4]);
cout << a << " has " << b << " bit(s)" << endl;
cout << argv[2] << "(base" << argv[3] << ")" << "=" << c << "(base" << argv[4] << ")" << endl;
return 0;
}
但是遇到以下问题
bitCounter.cpp:15:14: error: no matching function for call to 'converter'
string c = converter(argv[2], argv[3], argv[4]);
^~~~~~~~~
bitCounter.cpp:8:8: note: candidate function not viable: no known conversion from 'char *' to 'int' for 2nd argument; dereference the argument with *
string converter(string num, int base1, int base2);
我该如何解决?另外,我的转换功能是否在做它应该做的事情? 谢谢
【问题讨论】:
-
argv数组是一个字符串数组。您将这些字符串传递给converter函数,而无需转换为函数期望的int参数。 -
至于“我的转换函数是否在做它应该做的事情”,这就是为什么你应该学习如何使用调试器。
标签: c++ hex converters