0

我已经看到了使用指针的其他解决方案。我不太了解指针的工作原理,无法将它们实现到这个程序中。如果解决方案需要一个,有人可以解释为什么吗?我整晚都在用这个程序尝试各种事情,但一无所获。我阅读了练习所在的“The C Programming Language”书中的相关文本。我不能成为唯一被这个 D 难倒的人:

#include <stdio.h>
#include <math.h>
#include <ctype.h>

#define MAX 1000

int htoi(char s[]);


main()
{
char line[MAX];
int i, c;
printf("Enter the strig to convert to an integer:");
for(i=0; i<MAX && (c=getchar())!=EOF && c != '\n'; ++i)
    line[i] = c;
int a =0;
a = htoi(line);
printf("%d", a);

}  

int htoi(char s[])
{
int i, n, z;
n=0;
int total = 0;
for(i=0; s[i] != '\0'; ++i)
    {
        if (s[i] == 'a'||s[i] == 'A')
            n = 10;
        else if(s[i] == 'b'||s[i] == 'B')
            n = 11;
        else if(s[i] == 'c'||s[i] == 'C')
            n = 12;
        else if(s[i] == 'd'||s[i] == 'D')
            n = 13;
        else if(s[i] == 'e'||s[i] == 'E')
            n = 14;
        else if(s[i] == 'f'||s[i] == 'F')
            n = 15;
        else
            n = s[i];
        z = n * pow(16, i);
        total = total + z;
    }
return total;
}
4

2 回答 2

2

如果我错了,有人纠正我。但是你没有在你的 char 数组中放置一个空终止符:

for(i=0; i<MAX && (c=getchar())!=EOF && c != '\n'; ++i)
   line[i] = c;

稍后,你做

for(i=0; s[i] != '\0'; ++i)

但是由于您从未附加空终止符,因此上述 for 循环将遍历数组的边界,直到它在堆栈上的某处看到空值或出现段错误。

您应该执行以下操作:

for(i=0; i<(MAX-1) && (c=getchar())!=EOF && c != '\n'; ++i)
   line[i] = c;
line[i+1] = '\0';

注意(MAX-1)

PS 不要以 root 身份运行任何不需要 root 的东西,请参阅:最低权限原则

于 2013-08-02T15:40:32.017 回答
0

你的问题在这里:

else
        n = s[i]; // <- n is getting the character code value of S[i]

要解决,我建议这样做:

else
        n = s[i] - '0';

编辑:

你还有两个问题:

  1. 你需要空终止行字符(你的字符串没有'\ 0')
  2. 您正在反转幂数学(左边的数字比右边的数字更重要)

要解决 (1),请执行以下操作:

for(i=0; i<MAX && (c=getchar())!=EOF && c != '\n'; ++i)
    line[i] = c;
line[i] = '\0'; // <-- added here

要解决 (2),请执行以下操作:

int total = 0;
int len = strlen(s) - 1; // <- added here
...
z = n * pow(16, len - i); // <- change here

另一种方式,您可以避免使用昂贵的 pow 函数,只需将 4 位左移,如下面的代码所示:

代替:

z = n * pow(16, i);
total = total + z;

做:

total <<= 4;  // changed here
total += n;   // and here
于 2013-08-02T15:23:43.933 回答