【问题标题】:K&R C Programming Language Exercise 2-3 code returns rubbishK&R C 编程语言练习 2-3 代码返回垃圾
【发布时间】:2022-01-02 02:19:15
【问题描述】:

我试图从练习 2-3 中写出一个解决方案。编译后,它在输出时返回随机数。我真的不明白这个问题是从哪里来的。

任何帮助表示赞赏。

StackOverflow 不断要求提供更多详细信息。该程序的目的在下面的代码中列出。

更多细节。

代码目的:

编写函数 htoi(s),将一串 hexa- 十进制数字(包括可选的 0x 或 0X)到其 等效整数值。允许的数字是 0 到 9, a 到 f,A 到 F。

/*
 * Write the function htoi(s), which converts a string of hexa-
 * decimal digits (including an optional 0x or 0X) into its
 * equivalent integer value. The allowable digits are 0 through 9,
 * a through f, and A through F.
*/

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

int hti(char s)
{
        const char hexlist[] = "aAbBcCdDeEfF";
        int answ = 0;
        int i;

        for (i=0; s != hexlist[i] && hexlist[i] != '\0'; i++)
                ;
        if (hexlist[i] == '\0')
                answ = 0;
        else
                answ = 10 + (i/2);
        return answ;
}

unsigned int htoi(const char s[])
{
        int answ;
        int power = 0;
        signed int i = 0;
        int viable = 0;
        int hexit;

        if (s[i] == '0')
        {
                i++;
                if (s[i] == 'x' || s[i] == 'X')
                        i++;
        }
        const int stop = i;

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

        while (viable == 0 && i >= stop)
        {
                if (s[i] >= '0' && s[i] <= '9')
                {
                        answ = answ + ((s[i] - '0') * pow(16, power));
                }
                else
                {
                        hexit = hti(s[i]);
                        if (hexit == 0)
                                viable = 1;
                        else
                        {
                                hexit = hexit * (pow(16, power));
                                answ += hexit;
                        }
                }
                i--;
                power++;
        }
        if (viable == 1)
                return 0;
        else
                return answ;
}

int main()
{
        char test[] = "AC";
        int i = htoi(test);
        printf("%d\n", i);
        return 0;
}

【问题讨论】:

  • 调试器是个不错的起点。
  • hti 中,对于 '0' - '9' 的任何 ASCII 十六进制数字返回 0。不确定这是否是故意的。逻辑很绕。
  • 它在输出时返回随机数。,对于哪个输入?
  • answ 未在 htoi 中初始化。将其初始化为 0。您可以通过跟踪代码来发现这一点,或者通过使用调试器单步执行它并打印变量的值,或者通过插入 printf 语句来显示变量的值。您不应该使用 Stack Overflow 作为调试服务来找出您的程序。例如,您可以就 C 编程语言的工作原理提出具体问题,但您应该将任何问题隔离到程序的特定部分,而不是仅仅发布整个程序并期望其他人调试它。
  • hti() 中的循环体是空的,但可能应该包含if 语句作为循环体(最好用大括号括起来)。不要在整数计算中使用pow()。调整hti() 可能会更好,以便它为任何十六进制数字返回正确的值,而不是在htoi() 中使用一半代码(处理十进制数字的部分),在@987654331 中使用另一半(处理十六进制字母) @.

标签: c integer hex converters


【解决方案1】:

answ 未在 htoi 中初始化。将其初始化为零。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 2013-10-21
    相关资源
    最近更新 更多