16 進数を整数に変換するプログラムを C で作成しようとしています。8 進数を整数に変換するプログラムの作成に成功しました。しかし、文字 (af) を使い始めると問題が発生します。プログラムの私のアイデアは次の広告です。
パラメータは、0x または 0X で始まる文字列である必要があります。
パラメータの 16 進数は、文字列 s[] に格納されます。
整数 n は 0 に初期化され、ルールに従って変換されます。
私のコードは次のとおりです(K&Rのp37までしか読んでいないので、ポインターについてはあまり知りません):
/*Write a function htoi(s), which converts a string of hexadecimal digits (including an optional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through 9, a through f, and A through F.*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
int htoi(const char s[]) { //why do I need this to be constant??
int i;
int n = 0;
int l = strlen(s);
while (s[i] != '\0') {
if ((s[0] == '0' && s[1] == 'X') || (s[0] == '0' && s[1] == 'x')) {
for (i = 2; i < (l - 1); ++i) {
if (isdigit(s[i])) {
n += (s[i] - '0') * pow(16, l - i - 1);
} else if ((s[i] == 'a') || (s[i] == 'A')) {
n += 10 * pow(16, l - i - 1);
} else if ((s[i] == 'b') || (s[i] == 'B')) {
n += 11 * pow(16, l - i - 1);
} else if ((s[i] == 'c') || (s[i] == 'C')) {
n += 12 * pow(16, l - i - 1);
} else if ((s[i] == 'd') || (s[i] == 'D')) {
n += 13 * pow(16, l - i - 1);
} else if ((s[i] == 'e') || (s[i] == 'E')) {
n += 14 * pow(16, l - i - 1);
} else if ((s[i] == 'f') || (s[i] == 'F')) {
n += 15 * pow(16, l - i - 1);
} else {
;
}
}
}
}
return n;
}
int main(void) {
int a = htoi("0x66");
printf("%d\n", a);
int b = htoi("0x5A55");
printf("%d\n", b);
int c = htoi("0x1CA");
printf("%d\n", c);
int d = htoi("0x1ca");
printf("%d\n", d);
}
私の質問は次のとおりです。
1. htoi(s) の引数に const を使用しない場合、g++ コンパイラから次の警告が表示されます。
2-3.c: 関数 'int main()' 内: 2-3.c:93:20: 警告: 文字列定数から 'char*' への非推奨の変換 [-Wwrite-strings] 2-3.c:97 :22: 警告: 文字列定数から 'char*' への非推奨の変換 [-Wwrite-strings] 2-3.c:101:21: 警告: 文字列定数から 'char*' への非推奨の変換 [-Wwrite-strings] 2 -3.c:105:21: 警告: 文字列定数から 'char*' への非推奨の変換 [-Wwrite-strings]
どうしてこれなの?
2.プログラムの実行に時間がかかるのはなぜですか? 私はまだ結果を見ていません。
3. ターミナルで g++ 2-3.c の代わりに cc 2-3.c と入力すると、次のエラー メッセージが表示されるのはなぜですか。
「`pow' への未定義の参照」
累乗関数を使用したすべての行で?
4. 私のプログラムの他のエラー/改善の可能性を指摘してください。