【发布时间】:2014-10-12 04:40:55
【问题描述】:
在我的代码中,我需要能够将任何整数输入转换为 2 到 16 之间的所需基数。问题是虽然输出表明我的代码运行成功,但我没有得到任何输出。我在 NetBeans 和 linux 终端中尝试过。我的代码如下所示:
/*
* 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 语句,但这些语句也没有出现。任何信息都会有所帮助。
【问题讨论】:
-
嗯..
count >= 0在您的 for 循环继续条件中?好吧,count被声明为unsigned count;。您能想到任何 时间不会满足该条件吗? (不要说count何时小于零,因为它没有签名,所以这不会发生)。 -
for (p = newNum; decimal > 0; p++)的意图是什么? “while”条件不应该涉及p吗? -
如果你正在寻找 newNum 的结尾,“for (count = 0; count != '\0'; count++);”不会的。当 count == 0xFFFFFFFF 时,您没有遇到分段错误,我很惊讶。提示:0 == '\0'。
-
@RichardPennington 我用 gcc 编译器运行了代码,但确实遇到了分段错误。这段代码似乎有很多问题。
-
@Cubia 最好的教育是学习如何解决问题。他会想办法的。 ;-)