基础转换c

时间:2014-12-10 14:16:37

标签: c

请帮帮我。所以这是我的代码。我正试图使用​​递归转换整数,我遇到了问题。我不能让0退出。提前谢谢!

#include <stdio.h>

void convert_basis(int num,int base) {
    if(num > 0) {
        int rem = (num % base);
        convert_basis(num / base, base);
        printf("%d",rem);
    }
}

int main() {
    int num, base;
    printf("\t\t\tBase Conversion Numbers\n");
    printf("=============================================\n\n");

    do {
        printf("Input the numbers that you want to search[1-100][0 to exit]: ");
        scanf("%d", &num);
        fflush(stdin);
    } while (num<1 || num>100);

    do {
        printf("Input the number of base [2-20]: ");
        scanf("%d", &base);
        fflush(stdin);
    } while (base<2 || base>20);

    printf("\n\n");
    int flag=base;
    for(int i=flag; i>1; i--) {
        printf("Number %d in base %d is : ", num, base);
        convert_basis(num,base);
        base--;
        printf("\n");
    }
    printf("\n\nPress enter to continue.......");
    getchar();
    return 0;
}

2 个答案:

答案 0 :(得分:0)

尝试:

do {
    printf("Input the numbers that you want to search[1-100][0 to exit]: ");
    scanf("%d", &num);
    fflush(stdin);
    // Exit when user enters 0
    if (num == 0)
        return 0;
} while (num<1 || num>100);

或者,您可以使用exit(0);而非return 0,尤其是如果您要退出的功能不同于main

答案 1 :(得分:0)

请注意。

    printf("\n\nPress enter to continue.......");
    getchar();
    return 0;
}

将始终退出主程序。如果你想做另一个条目,你需要用循环包围输入do循环和递归逻辑。然后你可以使用0强制退出第一个输入do循环,如@sgvd

所示
相关问题