このメソッドは、特定の小数に収まる最大の 2 の累乗を見つけるために作成しました。数値ストレージでの入力オーバーフロー エラーを回避するために、10 進数は char 配列形式になっています。2 の累乗は、float の pow(2, power) 形式で計算されます。8.000000 次に、この数値をメソッドに送信して、ピリオドと末尾の 0 を削除します。すなわち。8.000000 は 8 になります
1 #include <string.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <memory.h>
5 #include <math.h>
6
7 int i;
16
17 void removeFloatZeros(char *floatvalue)
18 {
19 char *ptr = strchr(floatvalue, '.');
20 *ptr = '\0';
21 }
22
45
173 char *decimalToBinary(char *decimal)
174 {
176 int x;
177 double power = 0;
178 char *binary = malloc(sizeof(char *) * 1024);
179 char *twosPower = malloc(sizeof(char *) * 1024);
180
181 /* What is the greatest power of 2 that will fit into the decimal? */
182 for(x = 0; x <= 30; x++)
183 {
184 power = pow(2.0, x);
185 snprintf(twosPower, 1023, "%f", power);
186 removeFloatZeros(twosPower);
189 printf("strcmp(decimal, twosPower) = %d\n", strcmp(twosPower, decimal));
190 memset(twosPower, '\0', 1023);
191 }
214 }
215
216 int main(int argc, char*argv[])
217 {
218 char *dec1 = argv[1];
219 decimalToBinary(dec1);
220 return 1;
221 }
222
たとえば、argv[1] に 20 を入力すると、次のように出力されます。
strcmp(decimal, twosPower) = -1
strcmp(decimal, twosPower) = -1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = -1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = -1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = -1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = -1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = -1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = -1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = -1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = -1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = 1
strcmp(decimal, twosPower) = -1
これのどこが間違っているのですか?また、for ループの終了条件を無視します。6 回目の反復の前にすべて 1 を出力し、6 回目と 6 回目の反復後にすべて -1 を出力することになっています。