2014-10-12 45 views
-1

在我的代碼中,我需要能夠將任何整數輸入轉換爲2到16之間的所需基數。問題是雖然輸出狀態我的代碼成功運行,但我沒有輸出。我曾在NetBeans和Linux終端上試過。我的代碼如下所示:爲什麼我的C代碼不生成輸出?

/* 
* File: main.c 
* Author: Tyler Weaver 
* Assignment 1: Takes a decimal value and converts it to a desired base 
* 
* Created on October 11, 2014, 11:57 PM 
*/ 

#include <stdio.h> 

void toBase(unsigned decimal, unsigned base, char *newNum); 

int main(int argc, char** argv) { 
    const int MAX_LEN = 32; 
    char newNum[32]; 
    unsigned decimal, base; 

    printf("Enter a decimal value followed by a desired base: "); 
    scanf(" %u", &decimal); 
    scanf(" %u", &base); 

    toBase(decimal, base, newNum); 

    printf("%u equals ", decimal); 
    //Print the array out in reverse order 
    unsigned count; 
    for (count = 0; count != '\0'; count++); 
    for (count--; count >= 0; count--) { 
     printf("%c", newNum[count]); 
    } 
    printf(" (base-%u)\n", base); 

    return 0; 
} 

/** 
* Converts a number to desired base 
* @param decimal the number which to convert 
* @param base the base to convert decimal to 
* @param newNum the character array which to store the conversion 
*/ 
void toBase(unsigned decimal, unsigned base, char *newNum) { 
    const unsigned ASCII_DIFF = 97; 
    char *p; 

    for (p = newNum; decimal > 0; p++) { 
     unsigned temp = decimal % base; 

     *p = (temp < 10) ? temp : ((char) temp - 10 + ASCII_DIFF); 
    } 
} 

我的輸出在NetBeans:

Enter a decimal value followed by a desired base: 6 4 

RUN SUCCESSFUL (total time: 1s) 

似乎Linux終端上相同爲好。我曾嘗試在scanf語句之後放置printf語句,但這些語句不會出現。任何信息都有幫助。

+0

在您的for循環連續條件中,um ..'count> = 0'?那麼'count'被聲明爲'unsigned count;'。你能想到任何*時間,當這種情況不會得到滿足嗎? (並且不要說'count'小於零,因爲它沒有簽名,所以不會發生)。 – WhozCraig 2014-10-12 04:45:46

+0

'for(p = newNum; decimal> 0; p ++)'的意圖是什麼? 「while」條件不應該涉及「p」嗎? – wallyk 2014-10-12 04:47:26

+0

如果您正在尋找newNum的結尾,「for(count = 0; count!='\ 0'; count ++);」不會這樣做。我很驚訝,當count == 0xFFFFFFFF時,你沒有得到分段錯誤。提示:0 =='\ 0'。 – 2014-10-12 04:49:34

回答

0

您好像在toBase函數內運行了一個無限循環。

void toBase(unsigned decimal, unsigned base, char *newNum) { 
    const unsigned ASCII_DIFF = 97; 
    char *p; 

    for (p = newNum; decimal > 0; p++) { 
     unsigned temp = decimal % base; 

     *p = (temp < 10) ? temp : ((char) temp - 10 + ASCII_DIFF); 
    } 
} 

您使用decimal > 0作爲條件,但您永遠不會修改循環內的十進制值。

因此,在toBase()函數調用之後編寫的所有代碼都不會執行。

備註:我對「RUN SUCCESSFUL(總時間:1s)」有點困擾。用GCC編譯這個代碼並運行它給了我一個分段錯誤。結合無限循環問題,我高度懷疑程序已經「成功」結束。

+0

我在Netbeans上運行了代碼。它給了我一個「冉成功」,雖然沒有輸出。我被拋棄了,因爲它說「冉成功」。然而,我意識到我的代碼中的所有無限循環,並且我感謝你。 – 2014-10-12 05:05:34

+0

在我的linux實驗室裏,它並沒有說運行成功。它只是不顯示輸出。* – 2014-10-12 05:06:09

相關問題