【发布时间】:2020-12-14 21:30:23
【问题描述】:
我有这个程序试图在不使用 atoi 的情况下将字符串转换为不同的基数。为什么最后没有打印输出?文本 "Output:" 打印出来,但后面什么都没有。
在此之前代码似乎可以正常工作。我继续添加了空字节。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void Int(char* numstring, int base) {
char *digitPtr = numstring;
char ans[100];
int decVal = 0;
int totalVal = 0;
int numDigits = 0;
// Go through the entire string to get the decimal value of the number.
while (*digitPtr != '\0') {
numDigits++;
digitPtr++;
}
// Now calculate decimal value of the string.
printf("before decimal value calc \n");
// *digitPtr = numstring;
int length = numDigits;
numDigits--;
printf("numDigits: %d \n", numDigits);
for (int i = 0; i < length; i++)
{
printf("calcuating the dec \n");
decVal = (*numstring - 48);
printf("dec Value: %d \n", decVal);
printf("power: %f \n", pow(10, numDigits));
totalVal = totalVal + decVal * pow(10, numDigits);
printf("totalVal %d \n", totalVal);
numDigits--;
numstring++;
}
//*digitPtr = numstring;
numDigits = length;
printf("totalVal %d \n", totalVal);
while (totalVal > 0) {
int remainder = totalVal % base;
printf("remainder: %d \n", remainder);
totalVal = totalVal / base;
ans[numDigits] = remainder;
numDigits--;
}
ans[99] = '\0';
printf("Output: %s \n", ans);
}
int main() {
【问题讨论】:
-
ans[numDigits] = remainder + '0' -
另外,使用
numDigits作为索引看起来不正确。例如,如果有一个数字,那么它将存储到ans[1]而不是ans[0]。ans[99] = '\0';也是错误的,因为它将 NUL 放在数组的末尾而不是数字序列的末尾 - 结果是在printf将尝试解析为字符串的一部分的数字之后有垃圾。 -
无论如何,除非您将该功能作为家庭作业,否则您可以使用
strtol -
我收到了你的通知,说这不是家庭作业。 (但后来你删除了评论)在这种情况下你真的不需要重新发明轮子。
-
是的,这不是作业,而是你不应该使用这些功能的“挑战”