为什么我的C代码不能产生输出?

时间:2014-10-12 04:40:55

标签: c linux netbeans output

在我的代码中,我需要能够将任何整数输入转换为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语句,但是那些也没有出现。任何信息都会有所帮助。

1 个答案:

答案 0 :(得分: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编译此代码并运行它会给我一个分段错误。结合无限循环问题,我高度怀疑该程序已“成功”结束。