【发布时间】:2012-02-18 03:32:28
【问题描述】:
我编写此方法是为了找到适合给定小数的 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。
【问题讨论】:
-
您是否尝试过查看要比较的实际字符串,无论是在调试器中还是通过将它们与
strcmp的结果一起打印出来?我不认为strcmp坏了。 -
声称像
strcmp()这样的主流库函数行为不端是一个tyro 的标志。问题一定在于你如何使用它,而不是像这样的基础功能。 -
经过多年的编程,我自己在这种情况下的态度总是不假思索:“我一定是在犯错误”。每隔一年,我都会给自己一个惊喜……:-)
-
另外,你的两个 malloc 都是错误的。使用
sizeof(char)或不使用(仅 1024)。 -
是的,我试过并排打印它们,它们看起来很好。我并没有声称它工作不正常我只是想让你知道我做的某件事是错误的。