我编写了这个方法来找到适合给定小数的 2 的最大幂。十进制为 char 数组格式,以避免数字存储时出现输入溢出错误。2 的幂是用 float 的 pow(2, power) 格式计算的,即。8.000000 这个数字然后被发送到一个方法来删除句点和 0 的那个轨迹。IE。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。