在我的代碼中,我需要能夠將任何整數輸入轉換爲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語句,但這些語句不會出現。任何信息都有幫助。
在您的for循環連續條件中,um ..'count> = 0'?那麼'count'被聲明爲'unsigned count;'。你能想到任何*時間,當這種情況不會得到滿足嗎? (並且不要說'count'小於零,因爲它沒有簽名,所以不會發生)。 – WhozCraig 2014-10-12 04:45:46
'for(p = newNum; decimal> 0; p ++)'的意圖是什麼? 「while」條件不應該涉及「p」嗎? – wallyk 2014-10-12 04:47:26
如果您正在尋找newNum的結尾,「for(count = 0; count!='\ 0'; count ++);」不會這樣做。我很驚訝,當count == 0xFFFFFFFF時,你沒有得到分段錯誤。提示:0 =='\ 0'。 – 2014-10-12 04:49:34