簡體   English   中英

K&R C 編程語言練習2-3 代碼返回垃圾

[英]K&R C Programming Language Exercise 2-3 code returns rubbish

我試圖從練習 2-3 中寫出一個解決方案。 編譯后返回 output 上的隨機數。 我真的不明白這個問題是從哪里來的。

任何幫助表示贊賞。

StackOverflow 不斷詢問更多細節。 該程序的目的在下面的代碼中列出。

更多的延誤。

代碼的目的:

編寫 function htoi(s),它將十六進制數字字符串(包括可選的 0x 或 0X)轉換為其等效的 integer 值。 允許的數字是 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;
}

answ未在htoi中初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM